WordPress获取分类的顶级分类
摘要:wordpress子分类获取父分类 方法一 [crayon-623eca23456ee444426699…
摘要:wordpress子分类获取父分类 方法一 [crayon-623eca23456ee444426699/] 方法二 w…
wordpress子分类获取父分类
方法一
1
2
3
|
$p_id = get_the_ID();
$cat_srt = get_category_parents(get_the_category($p_id)[0] ,false, ‘|’);
$catParentName = explode(‘|’,$cat_srt)[0];
|
方法二
wordpress获取分类的顶级父类
第一个函数(get_term_top_most_parent)接受一个分类ID和分类 ,并返回分类的顶级父类(或本身);
第二功能(hey_top_parents)工作在循环中,以及,给定的分类法,返回后的分类顶层祖先。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
// 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;
}
|
类别:WordPress教程、
本文收集自互联网,转载请注明来源。
如有侵权,请联系 wper_net@163.com 删除。
还没有任何评论,赶紧来占个楼吧!