[How to] Display “Back to parent” Link on Pages
For a better seo, and a better user experience, you can easily add a “Back to parent” link on your pages. In this post i will show you how to add it to your page templates.
This will be done in two steps. First open functions.php
file in your wordpress theme directory and add the code below:
function stf_back_to_parent( $options ){ global $post; // Edit function defaults here $defaults = array( 'class' => 'read-more', 'before_link' => '← Back to ', 'after_link' => '', 'before' => '', 'after' => '' ) if( is_page() ){ // Display if this is a page // Get parent object $parent = &get_post( $post->post_parent ); $parent_title = isset( $parent->post_title ) ? $parent->post_title : ''; // If current page has a parent if( $parent_title != $post->post_title ) { extract( array_merge( $defaults, $options ) ); // Output our link echo $before . '<a class="'.$class.'" href="' . get_permalink( $post->post_parent ) . '" title="' . $parent_title . '">' . $before_link . $parent_title . $after_link . '</a>' . $after; } } }
This is a basic function to generate back to parent link. If you examine the code you can see there is a default options array you can edit, so you can easily customize the output as you like. To display the link, we need to call it in our page templates.
Now, open page.php
in your theme folder and add this simple code anywhere you like in your page template :
<?php stf_back_to_parent(); ?>
Save and upload your files.
Now when you visit a subpage on your site, you can see a link on top of your page. On top level pages, link will not be visible.
I hope you like it, Cheers!