1

I have the following php in a template. This lists the most recent posts.

<h2>Recent Posts</h2>
<ul>
<?php
    $args = array( 'numberposts' => '5', 'tax_query' => array(
            array(
                'taxonomy' => 'post_format',
                'field' => 'slug',
                'terms' => 'post-format-aside',
                'operator' => 'NOT IN'
            ), 
            array(
                'taxonomy' => 'post_format',
                'field' => 'slug',
                'terms' => 'post-format-image',
                'operator' => 'NOT IN'
            )
    ) );
    $recent_posts = wp_get_recent_posts( $args );
    foreach( $recent_posts as $recent ){
        echo '<li><a href="' . get_permalink($recent["ID"]) . '">' .   ( __($recent["post_title"])).'</a> </li> ';
    }
?>
</ul>

How can I make it so that each title displays the featured image of the article to the left of the text? I know that <?php the_post_thumbnail(); ?> will display the featured image but I am not sure how to incorporate this into the code.

EDIT: I would also like to display the post date (in human/relative style e.g "posted two days ago"). I also need to style this with a separate CSS class.

1

the_post_thumbnail() can only be used in "the Loop". What you need is get_the_post_thumbnail(). (See details and code examples on the code reference page).

So something like:

foreach( $recent_posts as $recent ){
    echo '<li>';
    echo get_the_post_thumbnail( $recent['ID'], 'size', array( 'class' => 'alignleft' ) );
    echo '<a href="' . get_permalink($recent["ID"]) . '">' .   ( __($recent["post_title"])).'</a></li> ';
}

Where 'size' is whatever registered thumbnail size you want for the image.

  • Ok thanks a lot! I got it to work now but on the top it says "scheduled" I don't know what line in the code that is causing this, but I guess that the php you gave me calls for post formats somewhere.. – Arete Apr 16 '16 at 23:30
  • You're probably picking up posts that are scheduled, but not yet published. You can limit to only the most recent published posts by adding 'post_status' => 'publish', to the beginning of your $args, just before 'numberposts'. – Caspar Apr 17 '16 at 0:17

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.