Few notes:
- Just use
the_title()
; instead ofecho get_the_title();
- Use
the_title_attribute()
for title attributes. - No need to override the global
$wp_query
when you use a secondary query. - Then use
wp_reset_postdata()
after your secondary query loop. - Use
the_permalink()
that escapes the permalink, instead of the unescapedecho get_permalink();
- There’s the
has_post_thumbnail()
to check if the post thumbnail is set. - Note that
get_the_post_thumbnail()
returns the post thumbnail image tag, not the url. - Check out
the_post_thumbnail_url()
to get the thumbnail url. - To check for the first item in your secondary recent posts loop, you can use
if( 0 === $recent_posts->current_post ){
within that loop.
Example:
Here’s an example (PHP 5.4+):
$recent_posts = new WP_Query( $args );
if( $recent_posts )
{
$thumbnail_url="https://example.tld/default.png"; // fallback post thumbnail url
$data = [];
// Loop
while( $recent_posts->have_posts() )
{
$recent_posts->the_post();
// Post thumbnail from the first post
if( 0 === $recent_posts->current_post )
$thumbnail_url = get_the_post_thumbnail_url( get_the_ID(), 'medium' );
// Collect post titles
$data[] = the_title(
sprintf(
'<div class="title"><h3><a href="https://wordpress.stackexchange.com/questions/246511/%s">',
esc_url( get_permalink() )
), // before
'</a></h2></div>', // after
false // echo
);
}
wp_reset_postdata();
// Output
if( $data )
printf(
'<div class="widget-wrap-sidebar" style="background-image: url(%s)">
<div class="my-widget">%s</div>
</div>',
esc_url( $thumbnail_url ),
join( '', $data )
);
}
Hope it helps.