1
<?php

$args = array(
    'post_type'      => 'page',
    'posts_per_page' => -1,
    'post_parent'    => $post->ID,
    'order'          => 'ASC',
    'orderby'        => 'menu_order'
 );


$parent = new WP_Query( $args );

if ( $parent->have_posts() ) : ?>

    <?php while ( $parent->have_posts() ) : $parent->the_post(); ?>

        <div id="parent-<?php the_ID(); ?>" class="parent-page">

            <h1><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h1>

            <p><?php // the_advanced_excerpt(); ?></p>

        </div>

    <?php endwhile; ?>

<?php endif; wp_reset_query(); ?>

This is my code. It should display the title of all child pages of any parent page. But, unfortunately, it just displays all the pages in the website including the child of the same and other pages as well.

Any suggestions on this?

1

You should use this attribute in the $args array to get children of specific page by Parent ID

'child_of' => 20,

More information: https://codex.wordpress.org/Function_Reference/get_pages

0

I just used this in a site! What about something like this:

function rt_list_child_pages() { 
global $post; 
if ( is_page() && $post->post_parent )

    $childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $post->post_parent . '&echo=0' );
else
    $childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $post->ID . '&echo=0' );
if ( $childpages ) {
    $string = '<ul>' . $childpages . '</ul>';
}
return $string;
}
add_shortcode('list-childpages', 'rt_list_child_pages');

The code above first checks to see if a page has a parent or the page itself is a parent. If it is a parent page, then it displays the child pages associated with it. If it is a child page, then it displays all other child pages of its parent page. Lastly, if this is just a page with no child or parent page, then the code will simply do nothing. In the last line of the code, I have added a shortcode, so you can easily display child pages without modifying your page templates.

To display child pages simply add the following shortcode in a page or text widget in the sidebar:

[rt-childpages]

or you can add the function

rt_list_child_pages()

to any page template.

  • Hey, Thanks for the heads up. Is that shortcode [rt-childpages] or [list-childpages]? – Mithun Nath Aug 11 '17 at 17:32
  • list-childpages. Sorry. – rudtek Aug 11 '17 at 17:45
  • did this answer your question? if so could you please mark as answered so the question can be closed? (it's the grey checkmark to the left of the question.) – rudtek Sep 4 '17 at 4:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.