I found this answer. It saved my day, but could you tell me how to display featured image of the post with the following code?
When I’m using
<?php echo $cpost->post_thumbnail('thumbnail', array('class' => 'alignleft')); ?>
An image does not show up…
Code below:
<?php if(is_page()) : // check we are a page ?>
<?php global $post; $cposts = get_posts("numberposts=-1&category_name={$post->post_name}"); if($cposts) : ?>
<?php foreach($cposts as $cpost) : ?>
<div class="mb20">
<h2><?php echo $cpost->post_title; ?></h2>
<p><?php echo $cpost->post_content; ?></p>
<?php echo $cpost->post_thumbnail('thumbnail', array('class' => 'alignleft')); ?>
</div>
<?php endforeach; ?>
<?php endif; ?>
<?php endif; ?>
Could you tell me how the correct code should work?
get_posts
fetches an array ofWP_Post
objects (see the return values ofget_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: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: