我有一个名为“产品”的自定义帖子类型。此CPT具有一个名为“功能”的布尔字段。
此刻我的产品循环按字母顺序排序:
{1, 2}
但是我该如何管理,首先显示所有特色产品(带有boolean = true),然后再显示所有其他产品(仍按字母顺序)?
答案 0 :(得分:0)
最简单的方法是使用2个参数并单独使用,此示例应根据数据库中“功能”键的元值起作用:
$args = array(
'post_type' => 'product',
'post_status' => 'any',
'orderby' => 'title',
'order' => 'ASC'
);
if ( ! empty( get_queried_object() ) ) {
$args['tax_query'] = array(
array(
'taxonomy' => 'product_categorie',
'field' => 'slug',
'terms' => get_queried_object()->slug
),
);
}
// Featured products args
$args1 = $args;
$args1['meta_query'] = array(
array(
'key' => 'featured',
'value' => 1, // Make sure that's 1 is the repersentation of true in db
'compare' '='
),
);
// Not freatured product args
$args2 = $args;
$args2['meta_query'] = array(
'relation' => 'OR',
array(
'key' => 'featured',
'value' => 0,
'compare' => '='
),
array(
'key' => 'featured',
'compare' 'NOT EXISTS'
),
);
答案 1 :(得分:0)
WP_Query
允许对数组使用多个orderby:
$args = array(
'post_type' => 'product',
'post_status' => 'any',
'meta_key' => 'featured',
'orderby' => array('meta_value' => 'DESC', 'title' => 'ASC')
);
$query = new WP_Query( $args );
请参阅:Order & Orderby parameters:多个orderby /订单对和具有“ meta_value”和自定义帖子类型的“ orderby”