在纯SQL
您可以使用逗号分隔的字符串来执行所需的操作,即ORDER BY post_type,post_name,post_date
. 然而WP_QUERY
不会允许这种事情发生。有一个rigid set of allowed values.
我可以想出几种方法来做到这一点。
您可以将查询变量“推”到WP_Query
只需将它们添加到$args
. Caveat: I do not know if this is intended behavior. It may be a quirk in the code base.
$args = array(
\'post_type\' => \'post\',
\'post_status\' => \'publish\',
\'posts_per_page\' => 8,
\'orderby\' => \'post_date,post_title\',
\'order\' => \'ASC\',
\'myorderby\' => \'post_date,post_name\'
);
$temp = $wp_query;
$wp_query = null;
$wp_query = new WP_Query();
$wp_query->query($args);
while ($wp_query->have_posts()) {
$wp_query->the_post();
echo $post->post_title.\'<br/>\';
}
在上添加筛选器
posts_orderby
...
function posts_odb_filter_wpse_96900($odb) {
global $wp_query;
$myodb = $wp_query->get(\'myorderby\');
if (!empty($myodb)) {
preg_match(\'/(ASC|DESC)$/\',$odb,$dir);
$odb = $myodb;
if (!empty($dir[0])) {
$odb .= \' \'.$dir[0];
}
}
return $odb;
}
add_filter(\'posts_orderby\',\'posts_odb_filter_wpse_96900\');
。。。你可以随心所欲地点菜。
更规范的方法是检查查询变量或其他信息,并相应地修改查询。
function posts_odb_filter_wpse_96900_v2($odb) {
global $wp_query;
if (is_front_page() && !is_main_query()) { // whatever conditions you need
preg_match(\'/(ASC|DESC)$/\',$odb,$dir);
$odb .= \' post_date,post_name \'.$dir[0];
}
return $odb;
}
add_filter(\'posts_orderby\',\'posts_odb_filter_wpse_96900_v2\');
第二种方法的缺点是,必须为需要更改的每个查询创建一个过滤器。