You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WP Query按_sale_price元键升序排序失效问题排查

问题:按_sale_price元字段排序WordPress产品时出现异常

尝试通过WP Query按_sale_price元字段对product类型文章进行升序排序,先后使用orderby参数为meta_value和meta_value_num的方式,但均返回错误排序结果——前20条正常,后续出现低价产品排在高价产品之后。

尝试过的WP Query参数

$args = array(
    'post_type'      => 'product',
    'order'          => 'ASC',
    'orderby' => 'meta_value',

    'meta_key' =>  '_sale_price',

    'posts_per_page'          => -1,

    'meta_query'     => array(
        array(
            'key'           => '_sale_price',
            'value'         => 0,
            'compare'       => '>',
            'type'          => 'NUMERIC'
        )
    )
);

$sale_books = new WP_Query($args);

尝试过的自定义SQL查询

global $wpdb;
$querystr = "
SELECT $wpdb->posts.*
FROM $wpdb->posts, $wpdb->postmeta
WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id
AND $wpdb->postmeta.meta_key = '_sale_price'
AND  $wpdb->postmeta.meta_value > 0
AND $wpdb->posts.post_status = 'publish'
AND $wpdb->posts.post_type = 'product'

ORDER BY $wpdb->postmeta.meta_value ASC";

还尝试对值进行类型转换:ORDER BY CAST(mt1.meta_value AS SIGNED) ASC,问题仍未解决。

所有产品都是simple类型,输出行索引和get_post_meta($row->ID,'_sale_price',true)值时,发现排序在第210条后开始混乱,低价产品出现在高价产品之后。

目前已通过usort函数解决该问题,但仍想了解原排序方式失效的原因:

function cmp($a, $b)
{

    $testa = floatval(get_post_meta($a->ID, '_sale_price', true));
    $testb = floatval(get_post_meta($b->ID, '_sale_price', true));

    return  $testa <=> $testb;
}

usort($pageposts, "cmp");

内容的提问来源于stack exchange,提问作者frank astin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 21:23:30