WordPress判断文章内是否有图片的方法

WordPress怎么判断文章内是否有图片?方法有很多种,下面记录下我使用过的判断文章知否有图片的方法。

1.判断是否有特色图片

使用内置函数has_post_thumbnail()判断文章是否设置过特色图片。

if (has_post_thumbnail()) {
    // 存在特色图片时执行的代码
    the_post_thumbnail(); // 调用特色图片
}

2.用正则匹配来检查文章内容中的图片

global $post;
$content = $post->post_content;
if (preg_match('/<img.*?src=["\'](.*?)["\']/i', $content)) {
    echo '文章包含图片';
}

3.最后结合下,确保万无一失。

首先写出封装方法,把下面方法添加到functions.php文件里

// WordPress判断文章内是否有图片
function has_post_image($post_id = null) {
    global $post;
    if (empty($post_id)) $post_id = $post->ID;
    
    // 判断特色图片
    if (has_post_thumbnail($post_id)) return true;
    
    // 判断内容图片
    $content = get_post_field('post_content', $post_id);
    return (bool) preg_match('/<img[^>]+>/i', $content);
}

使用方法:

while (have_posts()) : the_post();
    if (has_post_image()) {
        // 带图片的卡片布局
        the_post_thumbnail('medium');
        the_title('<h3>', '</h3>');
    } else {
        // 纯文字布局
        the_title('<h3 class="no-image">', '</h3>');
    }
endwhile;