如上所述,切勿使用query_posts
, 因为它破坏了很多东西。使用过滤器,如pre_get_posts
相反过滤器pre_get_posts
允许您在WP执行查询之前对其进行编辑。以下代码将按所需的元值排序。我这样做是为了使它只在页面的主查询和帖子类型上起作用post
, 但您可以对其进行编辑并进一步过滤:
function wpse194643_special_sort( $query ) {
//is this the main query and is this post type of post
if ( $query->is_main_query() && $query->is_post_type( \'post\' ) ) {
//Do a meta query
$query->set( \'meta_query\', array(
array( \'key\' => \'deadline\' )
) );
//sort by a meta value
$query->set( \'orderby\', \'meta_value\' );
$query->set( \'order\', \'DESC\' );
}
}
add_action( \'pre_get_posts\', \'wpse194643_special_sort\' );