WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Check if is parent or ancestor (4 posts)

  1. Harrison O.
    Member
    Posted 11 months ago #

    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.

  2. 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';
    ?>
  3. Harrison O.
    Member
    Posted 11 months ago #

    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 } ?>
  4. Awesome :)

    Thanks for posting your results!

Reply

You must log in to post.

About this Topic

Tags

No tags yet.