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

如何获取当前自定义文章的术语?动态实现及替代方案咨询

自定义文章类型面包屑导航的术语获取方案

一、获取当前自定义文章关联的分类术语

你当前使用的get_the_terms( $post->ID, 'curr_post_tax' )是正确方向,补充错误处理和结果提取逻辑后更健壮:

// 获取当前文章ID
$post_id = get_the_ID();
// 自定义分类法标识(你的curr_post_tax)
$taxonomy = 'curr_post_tax';
// 获取文章关联的术语集合
$terms = get_the_terms( $post_id, $taxonomy );

// 验证结果并提取术语信息
if ( $terms && ! is_wp_error( $terms ) ) {
    // 取第一个关联术语(若文章关联多个,可循环遍历处理)
    $target_term = reset( $terms );
    $term_name = $target_term->name; // 术语名称
    $term_url = get_term_link( $target_term ); // 术语归档页链接
}

二、动态获取当前文章的自定义分类法(curr_post_tax)

如果不确定当前文章对应的自定义分类法slug,可通过以下两种方法动态获取:

方法1:筛选当前文章类型支持的自定义分类法

// 获取当前文章类型的所有分类法对象
$all_taxonomies = get_object_taxonomies( get_post_type(), 'objects' );

// 排除WordPress内置分类法(分类、标签),保留自定义分类法
$custom_taxonomies = array_filter( $all_taxonomies, function( $tax ) {
    return ! in_array( $tax->name, [ 'category', 'post_tag' ] );
} );

// 遍历自定义分类法,找到当前文章关联的那个
foreach ( $custom_taxonomies as $tax ) {
    $terms = get_the_terms( get_the_ID(), $tax->name );
    if ( $terms && ! is_wp_error( $terms ) ) {
        $curr_post_tax = $tax->name; // 得到目标分类法slug
        break;
    }
}

方法2:直接获取当前文章关联的分类法

// 获取当前文章关联的所有分类法slug
$post_tax_slugs = get_post_taxonomies( get_the_ID() );

// 排除内置分类法,得到自定义分类法
$custom_tax_slug = array_diff( $post_tax_slugs, [ 'category', 'post_tag' ] );

if ( ! empty( $custom_tax_slug ) ) {
    $curr_post_tax = reset( $custom_tax_slug );
}

三、完整面包屑导航实现(对应「首页>目录>术语>当前产品」结构)

结合上述逻辑,写出适配需求的面包屑函数:

function custom_product_breadcrumb() {
    echo '<div class="breadcrumb">';
    // 首页
    echo '<a href="' . home_url() . '">首页</a>';

    // 自定义文章类型归档页(对应「目录」)
    $post_type = get_post_type();
    $post_type_obj = get_post_type_object( $post_type );
    if ( $post_type_obj ) {
        echo ' > <a href="' . get_post_type_archive_link( $post_type ) . '">' . $post_type_obj->labels->name . '</a>';
    }

    // 自定义分类术语(对应「术语」)
    $taxonomy = 'curr_post_tax';
    $terms = get_the_terms( get_the_ID(), $taxonomy );
    if ( $terms && ! is_wp_error( $terms ) ) {
        $term = reset( $terms );
        echo ' > <a href="' . get_term_link( $term ) . '">' . $term->name . '</a>';
    }

    // 当前文章标题(对应「当前产品」)
    echo ' > <span>' . get_the_title() . '</span>';
    echo '</div>';
}

// 在单页面模板中调用该函数即可输出面包屑
custom_product_breadcrumb();

四、其他替代思路

  • 若自定义分类术语存在层级关系(父术语>子术语),可在获取术语后递归遍历$term->parent,输出完整层级路径
  • 无需插件时,自定义函数是最灵活的方案;若依赖插件,Yoast SEO、Rank Math等SEO插件均支持自定义文章类型和分类法的面包屑配置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 22:32:43