Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Only display sub-nav if present WordPress

  • SOLVED

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

Answers (2)

2010-03-26

Brian Richards answers:

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.

2010-03-26

Buzu B answers:

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