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

WordPress归档页面替换JNews主题分类为文章标签实现问题

解决方案

你调用get_the_tags触发错误,主要是两个原因:一是没处理标签不存在或获取失败的场景,二是原代码通过字符串拼接返回HTML,不能直接在字符串里嵌入PHP代码块。以下是修正后的完整代码:

public function render_block_type_1( $post, $image_size ) {
    $post_id         = $post->ID;
    $box_shadow_flag = isset( $this->attribute['box_shadow'] ) && $this->attribute['box_shadow'] ? 'box_shadow' : '';
    $permalink       = get_the_permalink( $post );

    // 预先处理标签的HTML内容
    $tag_html = '';
    $tags = get_the_tags($post_id);
    // 判断标签是否存在且获取成功
    if ($tags && !is_wp_error($tags)) {
        // 取第一个标签(和原代码展示单个主分类的逻辑对齐)
        $first_tag = reset($tags);
        $tag_link = get_tag_link($first_tag->term_id);
        $tag_name = esc_html($first_tag->name);
        // 生成标签的HTML结构
        $tag_html = "<div class=\"jeg_post_category\">
                        <span><a href=\"{$tag_link}\">{$tag_name}</a></span>
                    </div>";
    }

    return '<article ' . jnews_post_class( 'jeg_post ' . $box_shadow_flag, $post_id ) . ">
                <div class='box_wrap'>
                    <div class=\"jeg_thumb\">
                        " . jnews_edit_post( $post_id ) . "
                        <a href=\"{$permalink}\">{$this->get_thumbnail($post_id, $image_size)}</a>
                        
                        {$tag_html}
                    </div>
                    <div class=\"jeg_postblock_content\">
                        <h3 class=\"jeg_post_title\">
                            <a href=\"{$permalink}\">" . get_the_title( $post ) . "</a>
                        </h3>
                        {$this->post_meta_1($post)}
                    </div>
                </div>
            </article>";
}

关键细节说明:

  • 增加了is_wp_error($tags)判断,避免标签获取失败时触发PHP错误
  • 用reset($tags)获取第一个标签,和原代码展示单个主分类的逻辑保持一致
  • 给标签添加了跳转链接,和原分类的交互逻辑统一;如果不需要链接,可去掉<a>标签,只保留{$tag_name}
  • 用esc_html()转义标签名称,避免XSS安全风险
  • 先将标签HTML生成后再拼接到返回字符串中,符合原函数的字符串拼接写法,不会触发语法错误

重要提醒:

直接修改主题核心文件会导致主题更新后代码丢失,建议使用子主题重写Block_37_View类,或者借助JNews主题提供的自定义钩子(若有)完成修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 12:15:33