wordpress 获取分类的顶级父类

// determine the topmost parent of a term
function get_term_top_most_parent($term_id, $taxonomy){
    // start from the current term
    $parent  = get_term_by( 'id', $term_id, $taxonomy);
    // climb up the hierarchy until we reach a term with parent = '0'
    while ($parent->parent != '0'){
        $term_id = $parent->parent;

        $parent  = get_term_by( 'id', $term_id, $taxonomy);
    }
    return $parent;
}

// so once you have this function you can just loop over the results returned by wp_get_object_terms

function hey_top_parents($taxonomy, $results = 1) {
    // get terms for current post
    $terms = wp_get_object_terms( get_the_ID(), $taxonomy );
    // set vars
    $top_parent_terms = array();
    foreach ( $terms as $term ) {
        //get top level parent
        $top_parent = get_term_top_most_parent( $term->term_id, $taxonomy );
        //check if you have it in your array to only add it once
        if ( !in_array( $top_parent, $top_parent_terms ) ) {
            $top_parent_terms[] = $top_parent;
        }
    }
    // build output (the HTML is up to you)


    foreach ( $top_parent_terms as $term ) {

          $r = '<ul>';
          $r .= '<li><a href="'. get_term_link( $term->slug, $taxonomy ) . '">' . $term->name . '</a></li>';
    }
          $r .= '</ul>';

    // return the results
    return $r;

}

第一个函数(get_term_top_most_parent)接受一个分类ID和分类 ​​,并返回分类的顶级父类(或本身); 

第二功能(hey_top_parents)工作在循环中,以及,给定的分类法,返回后的分类顶层祖先。


或者以下方法:

$cat_tree = get_category_parents($term_id, FALSE, ':', TRUE);
$top_cat = explode(':',$cat_tree);
$catParentSlug = $top_cat[0];


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值