Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer

up vote 0 down vote accepted

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>';
            }
        }
    }
?>
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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