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')); ?>

            <?php endforeach; ?>

                <?php endif; ?>
        <?php endif; ?>

Could you tell me how the correct code should work?


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:

    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:

    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>' .
                            array( 'class' => 'alignleft' )
                        ) .
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.