将这段代码加入主题的 functions.php 文件中
function catch_that_image() {
global $post, $posts;
// 获取特色图像的 ID
$thumbnail_id = get_post_thumbnail_id( $post->ID );
if ( $thumbnail_id ) {
// 如果存在特色图像,则获取其 URL 并返回
$first_img = wp_get_attachment_image_url( $thumbnail_id, 'full' );
} else {
// 如果没有特色图像,则从文章内容中抓取第一张图片的 URL
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+?src=[\'"]([^\'"]+)[\'"].*?>/i', $post->post_content, $matches);
if (!empty($matches[1]) && isset($matches[1][0])) {
$first_img = $matches[1][0];
} else {
// 设置随机图片
$cdn_url = 'https://你的域名'; // CDN 域名
$default_img_path = '/wp-content/themes/你的图片文件路径';
$random = mt_rand(1, 10);
$first_img = $cdn_url . $default_img_path . $random . '.jpg';
}
}
return $first_img;
}