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

Display children of parent, unless current post has children WordPress

  • SOLVED

Hi guys. Time to ask my first question at WP Questions!

I'm working on a website that has a horizontal top-level navigation. When one goes to one of the top-level pages, the children of that page are displayed in a vertical navigation to the left of the page content. When someone goes to a child page, I'd like for the children of the new page to be displayed in the vertical navigation, if children exist, if not, I'd like the children of the parent page to be displayed.

For example, a top-level page of the website is Artists. When I go to the Artists page, the Artists are listed in the vertical navigation on the left. When I go to an Artist's page, that Artist's albums are now listed in the vertical navigation instead.

This is the code I'm currently using:

<?php
global $wp_query;
if(empty($wp_query->post->post_parent))
{
$parent = $wp_query->post->ID;
}
else
{
$parent = $wp_query->post->post_parent;
}
?>

<?php if(wp_list_pages("title_li=&child_of=$parent&echo=0" )): ?>

<ul>
<?php wp_list_pages("title_li=&child_of=$parent" ); ?>
<?php echo $parent; ?>
</ul>
<?php endif; ?>


Unfortunately when you get to an artist's page, this fails out - as it lists all of the children of the artists page, and all of the children of each artist - so I get a long list of artists, albums and gallery pages.

I'm afraid I can't offer a live preview, because I'm using Theme Test Drive to build this on the live website, but I can provide screenshots if necessary.

Answers (1)

2010-01-30

Dan Fraticiu answers:

I think this should do the trick.

<ul>
<?php

global $post;

echo $post->ID;

$page_children = get_pages("child_of=".$post->ID."&sort_column=menu_order&depth=1");

if ($page_children) {

wp_list_pages('title_li=&child_of='.$post->ID.'&depth=1' );

}
else{
wp_list_pages('title_li=&child_of='.$post->post_parent.'&depth=1' );
}

?>
</ul>


Later edit:

A cleaner version, less code is always better.

<ul>
<?php
global $post;

$parent_id = get_pages("child_of=".$post->ID."&sort_column=menu_order&depth=1") ? $post->ID : $post->post_parent;

wp_list_pages('title_li=&child_of='.$parent_id.'&depth=1' );
?>
</ul>