'Wordpress list child pages on child page using foreach loop
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.
Solution 1:[1]
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
Solution 2:[2]
<? foreach (get_posts(array('post_type' => 'page','orderby' => 'title','order' => 'ASC','post_parent' => $post->ID)) as $p) { ?>
<?=$p->post_title; ?>
<? } ?>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Etienne Dupuis |
