Reputation: 1078
I'm using a foreach loop to list child pages on a parent page, which works great. However, the child pages don't list on a child page, which is what I'd like.
Here's what works for the parent page so far:
<?php
$nav = array(
'post_type' => 'page',
'orderby' => 'title',
'order' => 'ASC',
'post_parent' => $post->ID
);
$child_pages = get_posts($nav);
?>
<ul>
<?php foreach ($child_pages as $child_page) : ?>
<li>
<a href="<?=get_permalink($child_page->ID); ?>"><?=$child_page->post_title; ?></a>
</li>
<?php endforeach; ?>
</ul>
Ideally I'd like to keep using foreach rather than any other loop. I'm wondering if I need to add another loop inside my existing loop, but I'm unsure how to proceed.
Any help would be much appreciated.
Upvotes: 0
Views: 3529
Reputation: 13786
<? foreach (get_posts(array('post_type' => 'page','orderby' => 'title','order' => 'ASC','post_parent' => $post->ID)) as $p) { ?>
<?=$p->post_title; ?>
<? } ?>
Upvotes: 0
Reputation: 785
What you could do here is to check if the current page is a child page using wp_get_post_parent_id - see http://codex.wordpress.org/Function_Reference/wp_get_post_parent_id and then if the page is a child page - use the parent id, otherwise just use the post id. Something like this should work:
global $post;
if(wp_get_post_parent_id( $post->ID ))
{
$nav = array(
'post_type' => 'page',
'orderby' => 'title',
'order' => 'ASC',
'post_parent' => wp_get_post_parent_id( $post->ID )
);
}
else{
$nav = array(
'post_type' => 'page',
'orderby' => 'title',
'order' => 'ASC',
'post_parent' => $post->ID
);
}
$child_pages = get_posts($nav);
Upvotes: 2
Reputation: 1662
Use parent instead of post_parent
<?php
$nav = array(
'post_type' => 'page',
'orderby' => 'title',
'order' => 'ASC',
'child_of' => $post->ID
);
$child_pages = get_posts($nav);
?>
<ul>
<?php foreach ($child_pages as $child_page) : ?>
<li>
<a href="<?=get_permalink($child_page->ID); ?>"><?=$child_page->post_title; ?></a>
</li>
<?php endforeach; ?>
</ul>
hope it helps
Upvotes: 1