How to echo excerpts with wp_list_pages?

I’ve tried to echo excerpts in wp_list_pages with the code below. It works, but only for one of the child pages. How would I echo the excerpt and title for each child page?

<?php
$children = wp_list_pages('title_li=&depth=1&child_of='.$post->ID.'&echo=0');
if ($children) { ?>
    <h2>
        <?php echo $children; ?>
        <?php the_excerpt(); ?> 
    </h2>
<?php } ?>

Related posts

3 comments

  1. If you want to make use of all the nifty filters for the title and excerpt/content (and why would you not want that?) you should loop through a custom query instead of using get_pages and the pages’ plain contents:

    <?php
    $args = array(
        'post_type' => 'page',
        'post_status' => 'publish',
        'posts_per_page' => -1,
        'post_parent' => $post->ID,
    );
    $query = new WP_Query($args);
    while ($query->have_posts()) {
        $query->the_post();
        ?>
        <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
        <?php
        the_excerpt();
    }
    wp_reset_postdata();
    ?>
    
  2. wp_list_pages() is for displaying a list of pages. It looks like you want to do more with it.

    Instead you should use get_pages() with returns an array of data about the pages which means you have much more flexibility with it. Here’s some sample code:

    $children = get_pages(array('child_of' => $post->ID));
    
    foreach ($children as $child) { ?>
       <h2><?php echo $child->post_title; ?></h2>
       <p><?php echo $child->post_excerpt; ?></p>
       <li><a href="<?php echo get_permalink($child->ID); ?>"><?php echo $child->post_title; ?></a></li>
    <?php } ?>
    
  3. You can’t do this the way you are attempting. All of the markup is generated by wp_list_pages(). You can’t “insert” content like that.

    You can apply a callback to the wp_list_pages hook but you’d need some tricky regex to do it.

    I think your best option is to pass a custom Walker to wp_list_pages(). Something like this:

    class My_Page_Walker extends Walker_Page {
      function end_el( &$output, $page, $depth = 0, $args = array() ) {
        $output .= apply_filters('the_excerpt',$page->post_excerpt);  
        // or generate the excerpt from post_content
        // $output .= apply_filters('the_content',wp_trim_words($page->post_content));
        $output .= '</li>';
      }
    }
    
    $args = array(
      'post_status'=> 'publish',
      'walker' => new My_Page_Walker
    );
    
    wp_list_pages( $args ); 
    

Comments are closed.