复杂的WordPress订单参数:如何使用meta_value_num查询多个订单参数



这是我当前WP_Query的参数:

array(5) {
  ["posts_per_page"]=>
  int(6)
  ["orderby"]=>
  array(2) {
    ["uss_product_price"]=>
    string(3) "ASC"
    ["uss_product_weight"]=>
    string(4) "DESC"
  }
  ["meta_query"]=>
  array(3) {
    ["relation"]=>
    string(3) "AND"
    ["sortprimary_clause"]=>
    array(2) {
      ["key"]=>
      string(17) "uss_product_price"
      ["compare"]=>
      string(6) "EXISTS"
    }
    ["sortsecondary_clause"]=>
    array(2) {
      ["key"]=>
      string(18) "uss_product_weight"
      ["compare"]=>
      string(6) "EXISTS"
    }
  }
  ["paged"]=>
  string(1) "1"
  ["post_type"]=>
  string(7) "product"
}

在WordPress 4.0和4.2中引入了这种新的顺序:https://make.wordpress.org/core/2014/08/29/a-more-powerful-order-by-in-wordpress-4-0/https://make.wordpress.org/core/2015/03/30/query-improvements-in-wp-4-2-orderby-and-meta_query/

查询基本上工作,但是产品是根据uss_product_price和uss_product_weight的字符串值排序的。以前这个问题是通过在WP_Query中给出meta_value_num而不是meta_value来解决的:https://codex.wordpress.org/Class_Reference/WP_Query Order_.26_Orderby_Parameters

我希望结果按照uss_product_price(第一)和uss_product_weight(第二)的数值排序。我如何告诉查询使用数字值,同时仍然使用多个顺序参数的复杂性?

答案很简单-在元查询中添加'type' => 'numeric'。

array(5) {
  ["posts_per_page"]=>
  int(6)
  ["orderby"]=>
  array(2) {
    ["uss_product_price"]=>
    string(4) "DESC"
    ["uss_product_weight"]=>
    string(4) "DESC"
  }
  ["meta_query"]=>
  array(3) {
    ["relation"]=>
    string(3) "AND"
    ["sortprimary_clause"]=>
    array(3) {
      ["key"]=>
      string(17) "uss_product_price"
      ["compare"]=>
      string(6) "EXISTS"
      ["type"]=>
      string(7) "numeric"
    }
    ["sortsecondary_clause"]=>
    array(2) {
      ["key"]=>
      string(18) "uss_product_weight"
      ["compare"]=>
      string(6) "EXISTS"
    }
  }
  ["paged"]=>
  string(1) "1"
  ["post_type"]=>
  string(7) "product"
}

最新更新