我创建了一个自定义where子句。我用$wp_query->request
就在我的主循环之前,我对SQL真的不太了解,但这似乎可以让事情正常运行。
add_action(\'pre_get_posts\', \'add_trending_sort\', 11, 1);
function add_trending_sort($query){
if(!$query->is_main_query())
return;
//Overwrite query arguments
$query->set(\'meta_query\', array(
array(
\'key\' => \'TRENDING\',
//\'value\' => \'asdfasdf\',//may need a value for older versions of WordPress
\'compare\' => \'NOT EXISTS\',
)
));
$query->set(\'orderby\', \'meta_value_num date\');
$query->set(\'order\', \'DESC\');
}
add_filter(\'posts_where\', \'add_trending_where\');
function add_trending_where($where = \'\'){
global $wpdb, $wp_query;
if(!$wp_query->is_main_query())//Not sure if this really works. Should be OK
return $where;
$where .= " OR ( $wpdb->postmeta.meta_key = \'TRENDING\' )";
// Don\'t run this twice
remove_filter(\'posts_where\', \'add_trending_where\');
return $where;
}
或者,您可以设置
compare
到
\'EXISTS\'
并更改add\\u trending\\u where to中的行
$where .= " OR ($wpdb->postmeta.post_id IS NULL)";
. 然后只需在一个位置更改键的值。再一次,echo
$wp_query->request
如果你想更好地理解这一点或对其进行调整,可以尝试一下。
编辑:我刚刚注意到,如果meta_key
在查询上设置。你可以使用$query->set(\'meta_key\', NULL);
如果必须的话。
编辑2:我用上面的方法得到了这个。出于某种原因,一开始并不是这样(可能设置了meta\\u键……我不知道)。
add_action(\'pre_get_posts\', \'add_trending_sort\', 11, 1);
function add_trending_sort($query){
// Bail if not the main "hidden" query, as opposed to a \'new WP_Query()\' call
if(!$query->is_main_query())
return;
// Set meta_query to get shares for orderby, and also get non-shared content.
$query->set(\'meta_query\', array(
\'relation\' => \'OR\',
array(
\'key\' => \'TRENDING\',
\'compare\' => \'NOT EXISTS\',
),
array(
\'key\' => \'TRENDING\',
\'compare\' => \'EXISTS\',
)
));
//$query->set(\'meta_key\', NULL);
$query->set(\'orderby\', array(\'meta_value_num\' => \'DESC\', \'date\' => \'DESC\'));
}