Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get_pages( array( 'child_of' => $post->ID ) does not show all children

Tags:

wordpress

I am pretty new to wordpress, and wondering if someone could shed some light on this code. I am trying to list all sub pages on their parent page, here is the code with some html stripped out:

<?php
$mypages = get_pages( array( 'child_of' => $post->ID ) );

foreach( $mypages as $page ) {      
    $content = $page->post_content;
    if ( ! $content ) // Check for empty page
        continue;

    $content = apply_filters( 'the_content', $content );
?>

<p style="color: white; text-transform: uppercase;"><?php echo $page->post_title; ?></p>

<?php
   }   
?>

The code works, and correct sub pages are displayed - but not all of them. The 7 oldest posts are showing, but none of the newest pages that I created this week. I have checked and double checked that all new and old pages are the same in every way - same template, same parent page, same creator, same order number, and all published. Anyone have an idea of what I could be doing wrong?

like image 294
Alyssa Hope Avatar asked Oct 29 '22 12:10

Alyssa Hope


2 Answers

Try below code:

$args = array('child_of' => $post->ID,'sort_order' => 'desc',
'sort_column' => 'ID',
);
like image 173
Ash Patel Avatar answered Jan 02 '23 19:01

Ash Patel


I think you need additional argument as well to get result you are looking for.

$args = array( 
        'child_of' => $post->ID, 
        'parent ' => $post->ID,
        'hierarchical' => 0,
        'sort_column' => 'menu_order', 
        'sort_order' => 'asc'
);
$mypages = get_pages( $args );

You can check wordpress Doc for its argument and return output.

NOTE If you want to sort pages by date then you can change 'sort_column' => 'menu_order', with 'sort_column' => 'post_date',.

There is other method as well to achieve the same and I prefer below way.

<?php

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

$mypages = new WP_Query( $args );


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

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

        <p style="color: white; text-transform: uppercase;"><?php the_title(); ?></p>

    <?php endwhile; ?>

<?php endif; wp_reset_query(); ?>

You can also use wp_list_pages to render direct HTML.

like image 24
Rohil_PHPBeginner Avatar answered Jan 02 '23 20:01

Rohil_PHPBeginner