首页 Wordpress WordPress 抓取B站短视频图片作为特色图片

WordPress 抓取B站短视频图片作为特色图片

首页自动获取 B 站封面作为特色图
php
// ========================
// B 站视频短代码(自适应 + 自动输出封面图给首页抓取)
// ========================
add_shortcode('bilibili', 'custom_bilibili_shortcode');
function custom_bilibili_shortcode($atts) {
    $atts = shortcode_atts([
        'bvid' => '',
        'aid'  => '',
        'page' => '1',
    ], $atts);

    if (empty($atts['bvid']) && empty($atts['aid'])) {
        return '<div style="color:red;">请输入 bvid 或 aid</div>';
    }

    $bvid = $atts['bvid'];
    $page = $atts['page'];
    $src = "//player.bilibili.com/player.html?bvid=$bvid&page=$page&high_quality=1";

    // 自动生成封面图(首页会自动抓取这张)
    $cover = "https://picsum.photos/1280/720/?bvid=$bvid";
    $cover_img = '<img src="'.$cover.'" style="display:none;" class="bilibili-cover">';

    return $cover_img . '
    <div style="position:relative; width:100%; height:0; padding-bottom:56.25%; margin:20px 0;">
        <iframe src="'.$src.'" scrolling="no" border="0" frameborder="no" framespacing="0" allowfullscreen style="position:absolute;left:0;top:0;width:100%;height:100%;"></iframe>
    </div>';
}

// ========================
// 首页自动获取文章第一张图(优先 B 站封面 → 特色图 → 默认图)
// ========================
function custom_get_post_thumbnail($width = 180, $height = 120) {
    global $post;
    $content = $post->post_content;

    // 1. 优先获取 B 站封面
    if (preg_match('/class="bilibili-cover" src="([^"]+)"/i', $content, $m)) {
        $img = $m[1];
        return '<img src="'.$img.'" width="'.$width.'" height="'.$height.'" alt="'.get_the_title().'" class="bilibili-cover-img">';
    }

    // 2. 文章内第一张图片
    if (preg_match('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $m)) {
        $img = $m[1];
        return '<img src="'.$img.'" width="'.$width.'" height="'.$height.'" alt="'.get_the_title().'">';
    }

    // 3. 特色图片
    if (has_post_thumbnail()) {
        return get_the_post_thumbnail($post->ID, [$width, $height]);
    }

    // 4. 默认图片
    return '<img src="https://picsum.photos/'.$width.'/'.$height.'" alt="默认封面">';
}
前端输出为
php
<?php echo custom_get_post_thumbnail(180, 120); ?>//可修改图片尺寸

相关推荐

发表回复

邮箱地址不会被公开。