我不确定我的做法是否正确,似乎有很多人这样做,但从模板中的查询到函数,都有完全不同的方法,所以我不确定该走哪条路。
我有一个自定义的帖子类型(业务),其中包含特色帖子,每个帖子都有一个“featured\\u listing”post\\u meta,它可以是空的,也可以是附加到帖子的“featured listing”值**。我想在搜索结果和类别中显示那些没有空post\\u meta值的帖子。
**请注意值的-而不是\\u0。
这是我认为可能有效的方法,但我开始认为我找错了方向。
// Order posts by meta data
function custom_special_sort( $query ) {
//is this the main query and is this post type of post
if ( $query->is_main_query() && $query->is_post_type( \'business\' ) ) {
//Do a meta query
$query->get_post_meta(get_the_ID(), "featured_listing", TRUE);
//sort by a meta value
$query->set( \'orderby\', \'featured_listing\' );
$query->set( \'order\', \'ASC\' );
}
}
add_action( \'pre_get_posts\', \'custom_special_sort\' );
我也试着稍微改变一下,如下所示。但可以提供一些指导,说明为什么它不起作用,或者我是否做得正确: function custom_special_sort( $query ) {
// Check this is main query and other conditionals as needed
if ( $query->is_main_query() && $query->is_post_type( \'business\' ) ) {
$query->set(
\'meta_query\',
array(
array(
\'key\' => \'featured_listing\',
\'value\' => \'featured-listing\',
\'orderby\' => \'featured_listing\',
\'order\' => \'DESC\'
)
)
);
}
}
add_action( \'pre_get_posts\' , \'custom_special_sort\' );