how to get parent of parent post? (7 posts)

  1. Anonymous
    Posted 8 years ago #

    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?

  2. cgarcia109
    Posted 7 years ago #

    //$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

  3. nonbreakingspace
    Posted 7 years ago #

    @ 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.

  4. joshreisner
    Posted 7 years ago #

    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 . "

  5. joshreisner
    Posted 7 years ago #

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

  6. mikeque
    Posted 7 years ago #

    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.

  7. Peter Butler
    Posted 7 years ago #

    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);

Topic Closed

This topic has been closed to new replies.

About this Topic