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'); ?>
<h3><a 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
I’m fairly certain the problem is that some template tags rely on the global
$post
variable. Usingsetup_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:
Note: I cleaned up a few other things in your posted code. Also, I swapped out your custom
excerpt()
function withthe_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