WordPress 如果没有设置封面图片,那么调用文中第一张图片,否则调用封面图片的方法

如题,很多时候我们有这种需求,比如编辑忘记设置封面图片时。其实在 WordPress 中实现如果没有设置封面图

如题,很多时候我们有这种需求,比如编辑忘记设置封面图片时。其实在 WordPress 中实现如果没有设置封面图片,那么调用文中第一张图片,否则调用封面图片的方法非常简单,参考代码如下:

<?php
// 检查文章是否已经设置了封面图片
if ( has_post_thumbnail() ) {
    the_post_thumbnail(); // 显示设置的封面图片
} else {
    // 如果没有设置封面图片,则查找并显示第一张图片
    global $post;
    $first_img = '';
    ob_start();
    ob_end_clean();
    $output = preg_match_all('/<img.+src=['"]([^'"]+)['"].*>/i', $post->post_content, $matches);
    $first_img = $matches[1][0];
 
    if( !empty($first_img) ){
        echo '<img src="'.esc_attr($first_img).'" />';
    }
}
?>

在循环里调用:

<?php $query = new WP_Query( ['cat'=> 1,'posts_per_page' =>6] ); while ( $query->have_posts() ) : $query->the_post();?>
	<div class="swiper-slide">
		<a href="<?php the_permalink(); ?>">
			<?php
			if ( has_post_thumbnail() ) {
				the_post_thumbnail(array(180,130));
			}else {
				global $post;
				$first_img = '';
				ob_start();
				ob_end_clean();
				$output = preg_match_all('/<img.+src=['"]([^'"]+)['"].*>/i', $post->post_content, $matches);
				$first_img = $matches[1][0];

				if( !empty($first_img) ){
					echo '<img src="'.esc_attr($first_img).'"  width="180" height="130"/>';
				}
			}
			?>
			<span><?php the_title(); ?></span>
		</a>
	</div>
<?php endwhile; wp_reset_query();?>