get_the_terms
获取术语(int | object$post,string$taxonomy)
$post
(int | object)(必选)Post ID或object。
$taxonomy
(string)(必选)分类名称。
More details of
get_the_terms
获取条款
没有任何排序选项。但是,你可以用
usort
对返回的数组进行排序。
$terms = get_lowest_taxonomy_terms(get_the_terms( get_the_ID(), 'destinations' ));
这是一个如何使用
乌索特
$terms = get_the_terms( get_the_ID(), 'destinations' );
usort($terms,"so980_sort_terms_alphabetically");
function so980_sort_terms_alphabetically($a,$b) {
return $a['slug'] > $b['slug'];//using 'slug' as sorting order
}
so980_sort_terms_alphabetically
功能应该在你的主题中
functions.php
$terms = get_the_terms( get_the_ID(), 'destinations' );
usort($terms,"so980_sort_terms_alphabetically");
$terms = get_lowest_taxonomy_terms($terms);
更新
我刚刚测试了它,它返回了一个致命的错误,因为我犯了一个错误。错误消息:
Fatal error: Cannot use object of type WP_Term as array
获取条款
返回一个对象。所以,使用
$a['slug']
在这里,
function so980_sort_terms_alphabetically($a,$b) {
return $a->slug > $b->slug;//using 'slug' as sorting order
}
更新2
由于您的输出代码在您的问题中不可用,我将假设您正在循环内打印。而不是这样做,我们将把返回的项保存在另一个数组中,并在循环外对其排序,这样我们就可以一次获得所有的项。
下面是一个简单的例子,说明如何做到这一点:
if ($loop->have_posts()) :
while ($loop->have_posts()) : $loop->the_post();
$pre_terms = get_lowest_taxonomy_terms(get_the_terms(get_the_ID(), 'product_tag'));
if ( $pre_terms ) {
foreach ( $pre_terms as $pre_term ) {
$terms[] = $pre_term;
}
}
endwhile;
endif;
usort($terms,"so980_sort_terms_alphabetically");
//a quick test to see if it's working or not
foreach ( $terms as $term ) {
echo $term->slug;
echo '<br/>';
}