• Resolved Harris O.

    (@hfort)


    I need help with a code implementation. I am using the below code to display a specific widget on page parent (level 1) and child pages (level 2) however I realized I also need to have the widget on a third level (grand children) pages.

    To make it more clear, the code is working fine for the first two levels:
    > Parent (special widget shows)
    >> Child (special widget shows)
    >>> Grand Child ( special widget is not showing)

    This is the code:

    <?php if (is_page( '8' ) || '8' == $post->post_parent) { ?>
       Special widget
      <?php } else { ?>
      <?php } ?>

    Does anyone know how to implement this code to check if the page “8” is an ancestor?

    Thanks in advance.

Viewing 3 replies - 1 through 3 (of 3 total)
  • Here is the Codex for checking post ancestors.

    <?php if( count(get_post_ancestors($post->ID)) == 2 )
        echo 'this is grandchild of top page';
    ?>
    <?php if( count(get_post_ancestors($post->ID)) >= 2 )
        echo 'this is grandchild of some page';
    ?>
    Thread Starter Harris O.

    (@hfort)

    Thanks Josh. I was able to use a different method.

    Added to functions.php

    function is_tree( $pid ) {
        global $post;              
    
        if ( is_page($pid) )
            return true;    
    
        $anc = get_post_ancestors( $post->ID );
        foreach ( $anc as $ancestor ) {
            if( is_page() && $ancestor == $pid ) {
                return true;
            }
        }
        return false;
    }

    and the sidebar.php

    <?php if (is_page( '8' ) || '8' == $post->post_parent || is_tree('8')) { ?>
       Special widget
      <?php } else { ?>
      <?php } ?>

    Awesome ??

    Thanks for posting your results!

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Check if is parent or ancestor’ is closed to new replies.