logo

$5
Only display sub-nav if present

Hi Experts,

I built a custom page template that uses an if/else statement to display the child pages as a 'sub-nav' if there are child pages present. This logic works fine if you are on the parent page, but once you click on one of the child pages, the sub-nav goes away. How can I modify my code so that the sub-nav will show on all pages within the section?


<?php $children = wp_list_pages('&child_of='.$post->ID.'&echo=0'); if($children) : ?>
<div class="center">
<div id="horizontal_nav">
<ul>
<?php
if($post->post_parent)
$children = wp_list_pages("sort_column=menu_order&depth=1&title_li=&child_of=".$post->post_parent."&echo=0"); else
$children = wp_list_pages("sort_column=menu_order&depth=1&title_li=&child_of=".$post->ID."&echo=0");
if ($children) { ?>
<?php echo $children; ?>
<?php } ?>
</ul>
</div><!-- end horizontal_nav -->
</div><!-- end center -->
<?php endif; ?>

WP Answers | 03/26/10 at 12:25am | Edit


(2) Possible Answers Submitted...

  • avatar
    Last edited:
    03/26/10
    12:47am
    Brian Richards says:

    A simple way would be to modify the conditional at the very beginning of the statement to also include a check for the parent ID:

    <?php $children = wp_list_pages('&child_of='.$post->ID.'&echo=0'); if($children) : ?>


    becomes

    <?php
    $children = wp_list_pages('&child_of='.$post->parent.'&echo=0');
    if(!$children) { $children = wp_list_pages('&child_of='.$post->ID.'&echo=0'); }
    if ($children) : ?>


    First it uses the post's parent id, and if it doesn't have a parent then we use the current page ID. Everything else runs as normal.

    Previous versions of this answer: 03/26/10 at 12:43am

  • avatar
    Last edited:
    03/26/10
    12:55am
    Buzu B says:

    Well that is just normal since when you open the child page, the if returns false and the code within it is not executed.

    You will have to use

    get_post_ancestors($post->ID);

    to find out if the post you are currently reading has a parent. if it does then you get the child posts of the current post's parent just as you already do.

    try with something like this:

    $ancestors = get_post_ancestors($post->ID);
    if(!empty( $ancestors )){
    $parent = $ancestors[0];
    $children = wp_list_pages('&child_of='.$parent.'&echo=0');
    //print your children posts here...
    }


This question has expired.





Current status of this question: Completed