[英]Returning custom taxonomy in slug order
我有一个循环来拉入我想按段顺序排序的自定义分类法术语,但是当我添加“ orderby”命令时,我的循环中断了,什么也不返回。 毫无疑问,我使用的语法不正确,但是我看不出我的一生!
<?php
$loop = new WP_Query(
array(
'post_type' => 'camp',
'orderby' => 'name',
'order' => 'ASC',
'tax_query' => array(
array(
'taxonomy' => 'types',
'field' => 'slug',
'terms' => $term->slug,
),
)
)
);
if ($loop->have_posts()) :
while ($loop->have_posts()) : $loop->the_post();
$terms = get_lowest_taxonomy_terms(get_the_terms( get_the_ID(), array(
'taxonomy' => 'destinations',
'orderby' => 'slug',
'order' => 'ASC'
)) );
?>
任何帮助将不胜感激:)
添加了附加功能:
get_lowest_taxonomy_terms运行如下:
get_lowest_taxonomy_terms( $terms ) {
// if terms is not array or its empty don't proceed
if ( ! is_array( $terms ) || empty( $terms ) ) {
return false;
}
$filter = function($terms) use (&$filter) {
$return_terms = array();
$term_ids = array();
foreach ($terms as $t){
if( $t->parent == 0 ) {
$term_ids[] = $t->term_id;
}
}
foreach ( $terms as $t ) {
if( $t->parent == false || !in_array($t->parent,$term_ids) ) {
//remove this term
}
else{
$return_terms[] = $t;
}
}
if( count($return_terms) ){
return $filter($return_terms);
}
else {
return $terms;
}
};
return $filter($terms);
}
期望的输出
循环应查询分类法类型“目的地”,其中该目的地具有附加的分类法“类型”。
当前输出的屏幕抓图:
结果由CSS排序为3个列,但如您所见,并不是按字母顺序排序。
get_the_terms
不会将数组作为第二个参数。
get_the_terms(int | object $ post,字符串$ taxonomy)
参数:
$post
(int | object)(必需)帖子ID或对象。
$taxonomy
(字符串)(必需)分类名称。
默认情况下, get_the_terms
没有任何排序选项。 但是,您可以使用usort
对返回的数组进行排序。
因此,代码的最后一部分应该是:
$terms = get_lowest_taxonomy_terms(get_the_terms( get_the_ID(), 'destinations' ));
这是一个如何使用usort
对其进行排序的快速示例:
$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
。
get_the_terms
返回一个对象。 因此,使用$a['slug']
会导致错误。
在这里, so980_sort_terms_alphabetically
应该通过以下方式实现:
function so980_sort_terms_alphabetically($a,$b) {
return $a->slug > $b->slug;//using 'slug' as sorting order
}
**这已经过测试,并且可以正常工作。
由于您的问题中没有您的输出代码,因此我假设您正在循环中进行打印。 而不是这样做,我们将返回的术语保存在另一个数组中,并在循环外对其进行排序,以便我们可以一次获得所有术语。
这是一个简单的例子,说明了如何做到这一点:
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/>';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.