将最新的WordPress帖子的特色图像作为背景图像拉入css


Pull most recent WordPress post's featured image into css as a background-image

我正在尝试将最新帖子的特色图像拉到我网站顶部的div背景css中。

我目前有这个,这是我从这里的另一篇帖子中得到的

<?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] ); ?>')">

这是拉动当前页面的特色图像。寻找解决方案,以便找到最新的解决方案。

任何帮助都会很棒!:)

$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, '' );   
}
如果

存在特色图像,这应该检查最后 10 个帖子,如果找到,请将$src设置为该图像。如果未找到特色图片,则将其设置为此帖子精选图片。

如果您搜索WordPress Codex,它会有所帮助。您可以使用 wp_get_recent_posts() 获取最新的帖子 ID,然后使用它来get_the_post_thumbnail()。

例:

$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