我有一个带有人员类型分类法的人员职位类型(例如“Staff”)。在Person Type Term Archive页面上,我想按“排序名称”自定义字段排序。为此,我使用pre_get_posts
电话:
<?php
function my_query_tweaks( $query ) {
// stop immediately if we\'re in the admin or not working with the main query
if( is_admin() || !$query->is_main_query() )
return;
// order people by sortname
if( is_post_type_archive( \'ciswa_people\' ) || is_tax( \'ciswa_person_type\' ) ) {
$query->set( \'meta_key\', \'cis_sort_name\' );
$query->set( \'orderby\', \'meta_value\' );
$query->set( \'order\', \'ASC\' );
}
}
add_action( \'pre_get_posts\', \'my_query_tweaks\' );
然而,当我这样做时,术语归档页不会返回任何结果!注释掉
meta_key
line显示了正确的帖子,但当然是无序的。
当我查看WordPress正在生成的查询时,我认为问题在于WordPress也试图基于meta\\u键查询帖子,而不仅仅是按它排序。从…起$wp_query
在相关的空分类术语归档页面上:
["tax_query"]=>
object(WP_Tax_Query)#343 (2) {
["queries"]=>
array(1) {
[0]=>
array(5) {
["taxonomy"]=>
string(17) "ciswa_person_type"
["terms"]=>
array(1) {
[0]=>
string(5) "staff"
}
["include_children"]=>
bool(true)
["field"]=>
string(4) "slug"
["operator"]=>
string(2) "IN"
}
}
["relation"]=>
string(3) "AND"
}
["meta_query"]=>
object(WP_Meta_Query)#344 (2) {
["queries"]=>
array(1) {
[0]=>
array(1) {
["key"]=>
string(13) "cis_sort_name"
}
}
["relation"]=>
string(3) "AND"
}
。。。和
["request"]=>
string(498) "SELECT SQL_CALC_FOUND_ROWS fi_posts.ID FROM fi_posts INNER JOIN fi_term_relationships ON (fi_posts.ID = fi_term_relationships.object_id) INNER JOIN fi_postmeta ON (fi_posts.ID = fi_postmeta.post_id) WHERE 1=1 AND ( fi_term_relationships.term_taxonomy_id IN (6,10) ) AND fi_posts.post_type = \'ciswa_people\' AND (fi_posts.post_status = \'publish\' OR fi_posts.post_status = \'private\') AND (fi_postmeta.meta_key = \'cis_sort_name\' ) GROUP BY fi_posts.ID ORDER BY fi_postmeta.meta_value ASC LIMIT 0, 10"
SO网友:Johannes Pille
\'meta_key\' => \'keyname\'
必须是查询的一部分,才能按其值排序<遗憾的是,这将立即导致查询仅限于设置了键的帖子(其值可以为空,但必须存在)。
因此,要么考虑the method s_ha_dum linked to in the question comments, 或者选择在查询后进行排序。
让我提供一种方法(未经测试,只是一个概念):
function wpse105899_sort_posts_by_cis_sort_name( $a, $b ) {
$a_cis_sort_name = get_post_meta( $a->ID, \'cis_sort_name\', true );
$b_cis_sort_name = get_post_meta( $b->ID, \'cis_sort_name\', true );
if ( $a_cis_sort_name === $b_cis_sort_name ) {
return 0;
} else if ( $a_cis_sort_name > $b_cis_sort_name ) {
return 1;
} else {
return -1;
}
}
usort( $query->posts, \'wpse105899_sort_posts_by_cis_sort_name\' );
注:上述格式的条件
usort
回调的目的是提高可读性。在生产中,它可以是一个衬里:
function wpse105899_sort_posts_by_cis_sort_name( $a, $b ) {
$a_cis_sort_name = get_post_meta( $a->ID, \'cis_sort_name\', true );
$b_cis_sort_name = get_post_meta( $b->ID, \'cis_sort_name\', true );
return $a_cis_sort_name === $b_cis_sort_name ? 0 : ( $a_cis_sort_name > $b_cis_sort_name ) ? 1 : -1;
}