假设您想使用WordPress的帖子缩略图功能 ,但是有一个完整的帖子存档,这将花费太多时间。 对于新帖子,您可以具体指定并按预期使用该功能。 对于旧帖子,您只想使用它在缩略图内容中找到的第一张图像,如果没有,则使用默认图像。
将此添加到functions.php或制作功能插件 :
function catch_that_image() {
global $post, $posts;
$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)) {
$first_img = "/path/to/default.png";
}
return $first_img;
}
要使用它,请在循环中使用以下代码:
if ( get_the_post_thumbnail($post_id) != '' ) {
echo '<a href="'; the_permalink(); echo '" class="thumbnail-wrapper">';
the_post_thumbnail();
echo '</a>';
} else {
echo '<a href="'; the_permalink(); echo '" class="thumbnail-wrapper">';
echo '<img src="';
echo catch_that_image();
echo '" alt="" />';
echo '</a>';
}
我发现has_post_thumbnail不如上面的逻辑可靠。
翻译自: https://css-tricks.com/snippets/wordpress/get-the-first-image-from-a-post/