Support » Everything else WordPress » how to get parent of parent post?

  • hi again,

    $post->post_parent can tell you about the parent of your current page,

    if i wish to also check the grand parent of current page then how?



    is there some sort of code for this?

Viewing 6 replies - 1 through 6 (of 6 total)
  • //$post is an object with properties
    //$post->post_parent is the ID of the parent post (if any)

    if($post->post_parent) {
    $parent = get_post($post->post_parent);
    //now parent is an object describing the parent post

    @ cgarcia109: umm, that isn’t what he asked for. That’s just telling him how to set the parent of the current post to an object. He wants to know how to get the parent object of the parent object of the current post.

    i think cgarcia109 means that now that you have the parent object, you can query *its* parent, with $parent->post_parent. eg

    if ($post->post_parent) {
    //if you’re in a sub-page
    $parent = get_post($post->post_parent);
    if ($parent->post_parent) {
    //you’re in a grandchild
    $children = wp_list_pages(“title_li=&child_of=”.$parent->post_parent.”&depth=1&echo=0&sort_column=menu_order”);
    } else {
    //you’re on a child
    $children = wp_list_pages(“title_li=&child_of=”.$post->post_parent.”&depth=1&echo=0&sort_column=menu_order”);
    } else {
    //if you’re in the ancestor
    $children = wp_list_pages(“title_li=&child_of=”.$post->ID.”&echo=0&depth=1&sort_column=menu_order”);

    if ($children) echo ”

      ” . $children . “


    that last part didn’t come through correctly, but is not relevant. it’s just missing some HTML UL tags.

    This may not be exactly what you are looking for, but for the record I get a lot of mileage out of this simple conditional for testing if a page is a “grandchild” of a particular page:

    if ($parent->post_parent == ##) {
    // do something here

    Where ## is the id number of the parent’s parent.

    Here’s the function I wrote to get the topmost parent:

    function get_topmost_parent($post_id){
      $parent_id = get_post($post_id)->post_parent;
      if($parent_id == 0){
        return $post_id;
        return get_topmost_parent($parent_id);

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘how to get parent of parent post?’ is closed to new replies.