Child Pages Loop

If anyone can help that'd be great.

I've found a snippet of code that I've used which is pretty much doing what I want it to do, which lists out subpages of the parent, adds a thumbnail if there is one, and added a custom excerpt.

However, the problem is that I can't add individual ?php post_class(); ? to a div inside the loop, its using the class from the parent and repeating for the subpages.

?php
$child_pages = $wpdb-get_results("SELECT * FROM $wpdb-posts WHERE post_parent = ".$post-ID."    AND post_type = 'page' ORDER BY menu_order", 'OBJECT');    ?
?php if ( $child_pages ) : foreach ( $child_pages as $pageChild ) : setup_postdata( $pageChild ); ?

?php
// Must be inside a loop.
if ( has_post_thumbnail($pageChild-ID) ) {
get_the_post_thumbnail('page-thumb-mine');
}
//  else {
//  echo 'img src="' . get_bloginfo( 'stylesheet_directory' ) . '/images/icon-cropped.png" /';
//  }
?

div ?php post_class(); ?    
?php echo get_the_post_thumbnail($pageChild-ID, 'page-thumb-mine'); ?
h3a href="?php echo get_permalink($pageChild-ID); ?" rel="bookmark" title="?php     echo $pageChild-post_title; ?"?php echo $pageChild-post_title; ?/a/h3
?php echo excerpt(28); ?
/div
/div
?php endforeach; endif;
?

Any help would be appreciated!

Thanks

Andy

Topic loop child-pages post-class pages Wordpress

Category Web


I'm fairly certain the problem is that some template tags rely on the global $post variable. Using setup_postdata() as you are now, will not alter $post. If you replace all the instances of $pageChild with $post, everything should work.

However, I would strongly recommend using the WP_Query class and setting up your post data with 'the_post()' instead. Here is the equivalent of your code, but with WP_Query:

<?php
$args = array(
    'post_parent' => $post->ID,
    'post_type' => 'page',
    'orderby' => 'menu_order'
);

$child_query = new WP_Query( $args );
?>

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

    <div <?php post_class(); ?>>  
        <?php  
        if ( has_post_thumbnail() ) {
            the_post_thumbnail('page-thumb-mine');
        }
        ?>
        <h3><a href="<?php the_permalink(); ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></h3>
        <?php the_excerpt(); ?>
    </div>
<?php endwhile; ?>

<?php
wp_reset_postdata();

Note: I cleaned up a few other things in your posted code. Also, I swapped out your custom excerpt() function with the_excerpt() so the example code works for anyone that wants to copy/paste it.

References:

https://codex.wordpress.org/Class_Reference/WP_Query

https://codex.wordpress.org/Function_Reference/setup_postdata

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.