Reputation: 13
I'm trying to pull the most recent post's featured image into a div's background css for the top of my site.
I currently have this, which I got from another post on here
<?php $src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), array( 5600,1000 ), false, '' );?>
<div class="case-hero" style="background-image: url('<?php echo esc_url( $src[0] ); ?>')">
Which is pulling the featured image of the current page. Looking for a solution so it finds the most recent.
Any help would be great! :)
Upvotes: 0
Views: 192
Reputation: 766
$recent = get_posts( array('numberposts' => 10) );
$src = false;
foreach($recent as $p){
if( has_post_thumbnail( $p->ID ) ){
$src = wp_get_attachment_image_src( get_post_thumbnail_id($p->ID), array( 5600,1000 ), false, '' );
break;
}
}
if(!$src){
$src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), array( 5600,1000 ), false, '' );
}
This should check last the 10 posts if featured image exists and if found set the $src to that image. If featured image is not found it sets it to this post featured image.
Upvotes: 1
Reputation: 27102
It helps if you search the WordPress Codex. You can use wp_get_recent_posts() to get the most recent post ID, and then use that to get_the_post_thumbnail().
Example:
$recent_posts = wp_get_recent_posts( array('numberposts' => 1,) );
$most_recent_post_thumbnail = get_the_post_thumbnail( $recent_posts[0]['ID'] );
// Do whatever you want with $most_recent_post_thumbnail
Upvotes: 0