Add thumbnail to recent posts widget using filters

I want to add thumbnail to WordPress default recent posts widget, and I want to do it using any available filter.
Is there any filter know to this subject/topic

Solutions Collecting From Web of "Add thumbnail to recent posts widget using filters"

Here’s one way to do it through the the_title filter. We can limit the scope to the Recent Posts widget, by initialize it within the widget_posts_args filter and then remove it again after the loop.

/**
 * Recent Posts Widget: Append Thumbs
 */
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;
} );

where we define

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 ) . $title;

    return $title;
} 

and

function wpse_clean_up( \WP_Query $q )
{
    remove_filter( current_filter(), __FUNCTION__ );
    remove_filter( 'the_title', 'wpse_add_thumnail', 10 );
} 

Note that because of this check in the WP_Widget_Recent_Posts::widget() method:

get_the_title() ? the_title() : the_ID()

the the_title filter is applied two times for each item. That’s why we only apply the thumbnail appending for the odd cases.

Also note that this approach assumes non empty titles.

Otherwise it’s more flexible to just create/extend a new widget to our needs instead.

No filter available.


Checking the /wp-includes/widgets/class-wp-recent-posts-widget.php the following is the code that outputs the widget

$r = new WP_Query( apply_filters( 'widget_posts_args', array(
    'posts_per_page'      => $number,
    'no_found_rows'       => true,
    'post_status'         => 'publish',
    'ignore_sticky_posts' => true
) ) );

if ($r->have_posts()) :
?>
<?php echo $args['before_widget']; ?>
<?php if ( $title ) {
    echo $args['before_title'] . $title . $args['after_title'];
} ?>
<ul>
<?php while ( $r->have_posts() ) : $r->the_post(); ?>
    <li>
        <a href="<?php the_permalink(); ?>"><?php get_the_title() ? the_title() : the_ID(); ?></a>
    <?php if ( $show_date ) : ?>
        <span class="post-date"><?php echo get_the_date(); ?></span>
    <?php endif; ?>
    </li>
<?php endwhile; ?>
</ul>
<?php echo $args['after_widget']; ?>
<?php
// Reset the global $the_post as this query will have stomped on it
wp_reset_postdata();

endif;

Which obviously has no filter to insert some thumbnail or anything in the loop.