将多个值设置为AS SORT_COLUMN

时间:2013-09-22 作者:OZZIE

如果我想按1)menu\\u顺序排序,如果页面重量相同,我想2)按字母顺序排序,如何排序?如果设置menu\\u order,这是默认行为吗?

是吗?:

$args = array(
    \'sort_order\' => \'ASC\',
    \'sort_column\' => \'menu_order, post_title\'
);
$children = get_pages($args);
还是?:

$args = array(
    \'sort_order\' => \'ASC\',
    \'sort_column\' => \'menu_order post_title\'
);
还是?:

$args = array(
    \'sort_order\' => \'ASC\',
    \'sort_column\' => \'menu_order | post_title\'
);
还是?:

$args = array(
    \'sort_order\' => \'ASC\',
    \'sort_column\' => array(\'menu_order\', \'post_title\')
);
等等。。。

从wp\\u查询来看,它似乎是一个简单的空间?Multiple orderby values in WP_Query

应该真的在规范中。!

2 个回复
最合适的回答,由SO网友:s_ha_dum 整理而成

get_pages 爆炸sort_column 在逗号上(,) 性格Just check the source:

foreach ( explode( \',\', $sort_column ) as $orderby ) {
因此,正确的格式应该是您发布的第一个格式:

$args = array(
    \'sort_order\' => \'ASC\',
    \'sort_column\' => \'menu_order, post_title\'
);
$children = get_pages($args);
如果您没有看到预期的订单,可能是因为ASC 已应用。The ASC sort order is going to be applied to the last item in the list, not to all of them.

3755            $query = "SELECT * FROM $wpdb->posts $join WHERE ($where_post_type) $where ";
3756            $query .= $author_query;
3757            $query .= " ORDER BY " . $sort_column . " " . $sort_order ;
那个ASC 在完成ORDER BY 导致如下结果的语句:ORDER BY menu_order, post_title ASC. 我怀疑你想要ORDER BY menu_order ASC, post_titleORDER BY menu_order ASC, post_title ASC 相反

要获得这些结果之一,您需要使用WP_Query 因为get_pages 非常严格,不易过滤as it uses $wpdb->get_results directly.

不过,您仍然需要一个过滤器,因为WP_Query 手柄order 同样的方式get_pages

function alter_order_wpse_115183($orderby) {
  remove_action(\'posts_orderby\',\'alter_order_wpse_115183\');
  $pattern = \'([^ ]+) (ASC|DESC)$\';
  preg_match(\'/\'.$pattern.\'/\',$orderby,$matches);
  if (empty($matches[2])) {
    return $orderby;
  }
  if (!empty($matches[1])) {
    $order = str_replace(\',\',\' \'.$matches[2].\',\',$matches[1]).\' \'.$matches[2];
    // or
    // $order = str_replace(\',\',\' \'.$matches[2].\',\',$matches[1]);
  }
  return $order;
}
add_action(
  \'posts_orderby\',
  \'alter_order_wpse_115183\'
);
$args = array(
  \'post_type\' => \'page\',
    \'order\' => \'ASC\',
    \'orderby\' => \'menu_order title\'
);
$children = new WP_Query($args);
var_dump($children->request);

$children = new WP_Query($args);
var_dump($children->request); die;

SO网友:user68508

这在wp\\U list\\U页面中也非常有效:

<?php wp_list_pages(\'title_li=&sort_column=menu_order,post_title\'); ?>

结束

相关推荐