You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress自定义文章类型特色图片获取失败问题排查

自定义文章类型(Videos)特色图片无法显示问题排查

你的代码核心问题出在特色图片的调用方式上:

  • get_the_post_thumbnail() 函数本身会直接生成完整的 <img> 标签(包含src、alt等属性),但你把它嵌套在了自己写的 <img> 的 src 属性里,导致最终HTML结构错误,浏览器无法识别图片地址。

修正方案(二选一即可)

方案1:直接使用get_the_post_thumbnail()输出完整图片标签

替换原代码中图片部分的代码:

<div class="left-img"><?php echo get_the_post_thumbnail( get_the_ID(), 'full', array('class' => 'post-image', 'alt' => get_the_title()) ); ?></div>

这样会直接生成带正确class和alt属性的img标签,无需手动写<img>。

方案2:用get_post_thumbnail_url()获取图片URL

如果坚持自己写<img>标签,改用这个函数获取纯图片地址:

<div class="left-img"><img class="post-image" src="<?php echo esc_url( get_post_thumbnail_url( get_the_ID(), 'full' ) ); ?>" alt="<?php echo esc_attr( get_the_title() ); ?>"></div>

注意加上esc_url()和esc_attr()做安全过滤,同时用文章标题作为alt文本更合理。

完整修正后的代码示例

add_shortcode('get-video-post-type','videos_cpt');
function videos_cpt(){
    $args = array(
        'post_type' => 'Videos',
        'post_status'=>'publish',
    );
    $result = new WP_Query($args);
    if ($result->have_posts()){
        while($result->have_posts()){
            $result->the_post();
        ?>
        <div class="posts-carousel">
            <div class="item" id="video-box">
                <!-- 这里用方案1的写法 -->
                <div class="left-img"><?php echo get_the_post_thumbnail( get_the_ID(), 'full', array('class' => 'post-image', 'alt' => get_the_title()) ); ?></div> 
                <div class="right-content">
                    <h1 style="color:black;"><?php the_title();?></h1>
                    <p style="color:black;"><?php echo substr(get_the_excerpt(), 0,50); ?>....</p>
                    <a href="<?php the_permalink();?>">Read More</a>
                </div>
            </div>
        </div>
        <?php 
        }
    }
    wp_reset_postdata();
}

额外说明:原代码中id="show-all-post"放在循环里会生成重复的ID,违反HTML规范,已经移除该重复ID。

内容的提问来源于stack exchange,提问作者Sonali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 17:01:07