Home / functions.php / Display back to parent page link with get_post_ancestors
  • How to Display back to parent page link with get_post_ancestors

    display-back-to-parent-page-link-with-get_post_ancestors

    Adding the first snippet to the functions.php of your wordpress theme will display a link on sub pages back to the top level parent page. Place the second snippet within your theme in the location you want to display the link.

    ( click code to copy )

    wordpress snippet : PHP - functions.php

    <>
    function wps_parent_post(){
      global $post;
      if ($post->post_parent){
    	$ancestors=get_post_ancestors($post->ID);
    	$root=count($ancestors)-1;
    	$parent = $ancestors[$root];
      } else {
    	$parent = $post->ID;
      }
      if($post->ID != $parent){
          echo '<a href="'.get_permalink($parent).'" class="parent-post">Back to parent page</a>';
      }
    }
    
    ( click code to copy )

    wordpress snippet : PHP - single.php, index.php, page.php

    <>
    <?php
              wps_parent_post();
    ?>
    

    ( WordPress codex functions, hooks, in this snippet. )

    get_permalink, get_post, get_post_ancestors, wp,
  • Thanks for the snippet. Although it always points to the ‘root’ page, i.e. if I am on a grandchild page, it links to the grandparent instead of the parent.

  • Tim

    I used this on a site, but it is causing the top level pages to 404 unless I flush the rules regularly. Thoughts? Thanks