orderby price meta_value包含逗号 - wordpress

时间:2018-01-16 08:32:14

标签: php wordpress sorting sql-order-by

我的帖子应按价格自定义字段排序(从高到低)。使用以下选项正确排序:

选项1

$args = array(
    'posts_per_page' => -1,
    'post_type' => 'my-post-type', 
    'post_status' => 'publish',
    'meta_key' => 'price_field',
    'orderby' => 'meta_value_num',
    'order' => 'DESC',
);
$list = get_posts($args);

选项2

global $wpdb;
$queryStr = "SELECT * FROM wp_posts AS table1 LEFT JOIN (SELECT * FROM wp_postmeta WHERE 
meta_key = 'price_field') AS table2 ON table1.ID = table2.post_id WHERE 
table1.post_type = 'my-post-type' AND table1.post_status = 'publish' order by 
table2.meta_value+0 DESC";
$list = $wpdb->get_results($queryStr);

选项3 (与使用REPLACE功能的选项2相同)

$queryStr = "SELECT * FROM wp_posts AS table1 LEFT JOIN (SELECT * FROM wp_postmeta WHERE 
meta_key = 'price_field') AS table2 ON table1.ID = table2.post_id WHERE 
table1.post_type = 'my-post-type' AND table1.post_status = 'publish' order by 
REPLACE(table2.meta_value, ',', '') DESC";

帖子的订购方式如下(错误顺序):

600
25,000
22,000
15,000
10,000
7,000
6,000
2,000
0

排序很好,直到我添加600价格的帖子。只要它没有逗号,就会出现在循环的开头,这是不正确的。

有什么我错过的吗?

1 个答案:

答案 0 :(得分:1)

您可以在order by子句中使用(假)lpad构建有效订单,例如:

txt     id1   id2   id3 
Slim     2     1    11
Claws    3     1    11
Fluffy   10    1    11
Fang     11    1    11
Buffy    20    1    11
Bowser   31    1    11

参考: -

String Functions

或者根据您已签名的事实,您可以尝试转换

$queryStr = "SELECT * 
             FROM wp_posts AS table1 
             LEFT JOIN (SELECT * 
             FROM wp_postmeta 
             WHERE meta_key = 'price_field') AS table2 ON table1.ID = table2.post_id 
             WHERE  table1.post_type = 'my-post-type' AND table1.post_status = 'publish' 
             order by  lpad(table2.meta_value, 12, '0') ASC";