Site icon Experience Wordpress Developer Online – Design Develop and Maintenance Support

Add thumbnail to recent posts widget in WordPress

You are very familiar with WordPress recent post widget that display recent post entries from your blog. This widget has some setting as Title, number of posts to display etc but can you notice that widget display only date and title not the thumbnail.

So if you want to add thumbnail to recent posts widget in WordPress, than here is solution. Add below line of code at the end of your theme’s functions.php file of your active child theme (or theme) and Save the file.

add_filter( 'widget_posts_args', function( array $args )
{
    add_filter( 'the_title', 'wpse_prepend_thumbnail', 10, 2 );
    add_action( 'loop_end',  'wpse_clean_up' );
    return $args;
} );


function wpse_prepend_thumbnail( $title, $post_id )
{
    static $instance = 0;

    // Append thumbnail every second time (odd)
    if( 1 === $instance++ % 2 && has_post_thumbnail( $post_id ) )
        $title = get_the_post_thumbnail( $post_id, array( 50, 50)) .'

' . $title.'

'; return $title; } function wpse_clean_up( \WP_Query $q ) { remove_filter( current_filter(), __FUNCTION__ ); remove_filter( 'the_title', 'wpse_add_thumnail', 10 ); }
Exit mobile version