get_posts
fetches an array of WP_Post
objects (see the return values of get_post
for a complete list of object properties).
In your above code snippet, you are iterating over said array with a foreach
loop. Inside it, you are currently attempting to use a non-existent method ( post_thumbnail()
) of those objects.
Instead, make use of the get_the_post_thumbnail
function and feed it the current post objects’ ID property as a first argument:
<?php
echo get_the_post_thumbnail( $cpost->ID, 'thumbnail', array( 'class' => 'alignleft' ) );
?>
That answers the core of your question.
As an aside, let me point out that you do not need <?php
opening and closing tags on every line. So here’s a complete revision of your snippet:
<?php
if ( is_page() ) {
global $post;
$cposts = get_posts( array(
'posts_per_page' => -1,
'category_name' => $post->post_name
));
if ( $cposts ) {
foreach ( $cposts as $cpost ) {
echo '<div class="mb20">' .
'<h2>' . $cpost->post_title . '</h2>' .
'<p>' . $cpost->post_content . '</p>' .
get_the_post_thumbnail(
$cpost->ID,
'thumbnail',
array( 'class' => 'alignleft' )
) .
'</div>';
}
}
}
?>