Search code examples
phpwordpressnavigationchildrensiblings

In WordPress, how can I only show something in a page has children pages?


I have this code, which automatically generates a vertical navigation based on the current pages children or sibling pages. How can I modify this, so that if there are no children or sibling pages, the <ul> doesn't show up? I'm pretty new to both PHP and WordPress, so sorry if this is a stupid question.

<ul>
    <?php
        global $wp_query;
        if( empty($wp_query->post->post_parent) ) {
            $parent = $wp_query->post->ID;
        } else {
            $parent = $wp_query->post->post_parent;
        }
        wp_list_pages ("&title_li=&child_of=$parent");
    ?>
</ul>

Solution

  • You could try

    <?php
    
    global $wp_query;
    
    if( empty($wp_query->post->post_parent) ) {
        $parent = $wp_query->post->ID;
    } else {
        $parent = $wp_query->post->post_parent;
    }
    
    $children = get_pages('child_of='.$parent);
    
    if( count( $children ) > 0 ) { ?>
        <ul>
           <?php wp_list_pages ("&title_li=&child_of=$parent"); ?>
        </ul>
    <?php }