orderby price meta_value 其中包含逗号 - wordpress

orderby price meta_value which contains comma - wordpress

我有 post 应该按价格自定义字段排序(从高到低)。使用以下选项正确排序它们:

选项 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(与选项 2 相同,只是带有 REPLACE 函数)

$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

排序很好,直到我添加 post 和 600 价格。只要它里面没有逗号,它就会出现在循环的最开始,这是不正确的。

有什么我遗漏的吗?

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

$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";

参考:-

String Functions

或者根据你有 signbe 的事实,你可以尝试转换

$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  CONVERT(REPLACE(table2.meta_value, ',', ''),SIGNED INTEGER) ASC";