I’m trying to use the latest post featured image as a background image for a div on my homepage. Can anyone help with the php?
Advertisement
Answer
wp_get_recent_posts() will return a single, most recently published post using the parameters below.
I recommend placing the style in a stylesheet.
/* Get Recent Post */ $recent_post = wp_get_recent_posts(array( 'numberposts' => 1, 'post_status' => 'publish' )); /* If Featured Image Set */ if ( has_post_thumbnail($recent_post[0]['ID']) ){ /* Get Image */ $image = wp_get_attachment_image_src( get_post_thumbnail_id($recent_post[0]['ID']), 'full'); /* Output Div with Image Set Inline, Use padding Top for Responsive Ratio Size */ echo ' <div class="featured-image-div" style="background-image:url('.$image[0].');"></div> <style> .featured-image-div{ padding-top: calc( 450 / 800 * 100% ); background-size: contain; background-repeat: no-repeat; } </stle> '; }