我有一个名为Jobs的自定义帖子类型,它还包括自定义的分类法工作类别。到目前为止,我以以下方式显示我的内容(有效(:
<div class="col-lg-10">
<?php
$terms = get_terms([
'taxonomy' => 'work-category',
'hide_empty' => true,
'orderby' => 'count',
'order' => 'DESC',
]);
if ($terms) {
foreach ($terms as $category) { ?>
<h2 class="category-h2">
<?= $category->name ?>
</h2>
<?php
$posts = get_posts(array(
'posts_per_page' => -1,
'post_type' => 'jobs',
'tax_query' => [
[
'taxonomy' => 'work-category',
'field' => 'term_id',
'terms' => $category->term_id,
]
]
));
if ( $posts ) {
foreach( $posts as $post ) {
setup_postdata( $post );
include 'WorkView.php';
};
wp_reset_postdata();
}
}
} else { //no categories
$posts = get_posts(array(
'posts_per_page' => -1,
'post_type' => 'career'
));
if ( $posts ) {
foreach( $posts as $post ) {
setup_postdata( $post );
include 'JobListThumb.php';
};
wp_reset_postdata();
}
}
?>
</div>
我决定再添加一个名为";表演总是在最后";。为此,我创建了一个自定义字段(名称:stick_to_end(,专门用于该特定分类法(工作类别(中的术语。所以简单地说,我试图实现的是显示所有作品的类别,并按计数排序,但在最后仍然显示特定的作品(所以有点像粘性帖子/类别,但相反(。我已经试过了:
1. An array in orderby so `'orderby' => array ('count' => DESC, 'stick_to_end' => ASC)`
2. meta_query
<code>
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'count',
'value' => EXISTS,
),
array(
'key' => 'stick_to_end',
'compare' => '=',
'value' => false,
),
)
但这也不起作用。如何做到这一点,或者我在哪里犯了错误?
if您正在使用的get_terms
在内部使用WP_Term_Query
,它不支持像WP_Query
那样按多个键排序。
因此,这里有一个自定义方法,可以在查询后对它们进行排序。
usort( $terms, function( $a, $b ) {
$a_ste = (int) get_term_meta( $a->term_id, 'stick_to_end', true );
$b_ste = (int) get_term_meta( $b->term_id, 'stick_to_end', true );
if ($a_ste == $b_ste) return 0;
return ($a_ste < $b_ste) ? -1 : 1;
} );
将此代码放在if ($terms) {
之前
如果这对你有用,请告诉我。