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

如何仅在自定义文章类型的分类页面显示标签

解决方案:在seekers分类页面仅显示对应自定义文章类型的标签

问题分析

你当前使用的get_tags()函数默认会返回所有post_tag类型的标签,没有做任何过滤,所以会显示全站所有标签。要实现仅显示当前seekers-type分类下的seekers自定义文章类型对应的标签,需要先定位到当前分类下的目标文章,再基于这些文章过滤标签。

修改后的代码

方法1:自定义标签列表输出

将你原来的标签代码替换为以下内容:

// 获取当前 seekers-type 分类对象
$current_term = get_queried_object();

// 查询当前分类下所有 seekers 文章的ID集合
$post_ids = get_posts(array(
    'post_type'      => 'seekers',
    'tax_query'      => array(
        array(
            'taxonomy' => 'seekers-type',
            'field'    => 'term_id',
            'terms'    => $current_term->term_id,
        ),
    ),
    'fields'         => 'ids', // 仅返回文章ID,提升查询效率
    'posts_per_page' => -1     // 获取该分类下所有文章
));

// 输出标签列表
if (!empty($post_ids)) {
    $tags = get_tags(array(
        'object_ids' => $post_ids, // 仅获取指定文章关联的标签
        'orderby'    => 'name',
        'order'      => 'ASC'
    ));

    $html = '<ul>';
    foreach ($tags as $tag) {
        $tag_link = get_tag_link($tag->term_id);
        $html .= '<li>';
        $html .= "<a href='{$tag_link}' title='{$tag->name} 标签' class='{$tag->slug}'>{$tag->name}</a>";
        $html .= '</li>';
    }
    $html .= '</ul>';
    echo $html;
} else {
    echo '<p>暂无相关标签</p>';
}

方法2:使用WordPress内置标签云函数(更简洁)

如果不需要自定义太多样式,也可以用wp_tag_cloud()直接生成标签列表:

$current_term = get_queried_object();
$post_ids = get_posts(array(
    'post_type'      => 'seekers',
    'tax_query'      => array(
        array(
            'taxonomy' => 'seekers-type',
            'field'    => 'term_id',
            'terms'    => $current_term->term_id,
        ),
    ),
    'fields'         => 'ids',
    'posts_per_page' => -1
));

if (!empty($post_ids)) {
    wp_tag_cloud(array(
        'object_ids' => $post_ids,
        'taxonomy'   => 'post_tag',
        'format'     => 'list' // 以列表形式输出,也可改为'flat'等其他格式
    ));
} else {
    echo '<p>暂无相关标签</p>';
}

代码说明

  1. get_queried_object():获取当前页面对应的seekers-type分类对象,拿到分类ID用于后续文章查询。
  2. get_posts():精准筛选出当前分类下的所有seekers类型文章,仅返回ID集合以减少资源消耗。
  3. get_tags()/wp_tag_cloud():通过object_ids参数限制仅获取指定文章关联的标签,实现了仅显示目标标签的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 16:48:36