php - 包含逗号的 orderby price meta_value - wordpress

标签 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(与选项 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

在我添加价格为 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

或者根据您已经登录的事实,您可以尝试转换

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

关于php - 包含逗号的 orderby price meta_value - wordpress,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48276963/

相关文章:

java - 如何逐列而不是逐行填充二维数组

python - 按内部列表的特定索引对列表列表进行排序

C 排序算法没有输出正确的值?

php - .htaccess 使用 WordPress 插件重写

php - 如何在 Wordpress 上使用 php 将图像设置为帖子的特色图像?

php - 在 PHP 中存储类变量的最佳方式是什么?

php - 如何使用 php 循环遍历该数组并在每一行中打印一个结果

javascript - 如何在 Avada 主题中插入 jQuery 代码?

php - SQL查询如何从多行返回数据

php - 导入注释的问题