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

WordPress产品按价格从低到高排序时如何将无价格产品排在末尾

实现方案

你只需要调整查询参数的meta_query和orderby配置即可,修改后的完整代码如下:

$args = array(
    'post_type'      => 'product',
    'paged'          => $paged,
    'posts_per_page' => 15,
    'post_status'    => 'publish',
    'meta_query'     => array(
        'relation' => 'OR',
        // 标记存在价格的产品
        'has_price' => array(
            'key'     => '_price',
            'compare' => 'EXISTS',
        ),
        // 标记未设置价格的产品
        'no_price' => array(
            'key'     => '_price',
            'compare' => 'NOT EXISTS',
        )
    ),
    'orderby' => array(
        'has_price' => 'DESC', // 优先将存在价格的产品排在前面
        'meta_value_num' => 'ASC', // 有价格的产品按价格从低到高排序
    ),
    'meta_key'  => '_price',
    'tax_query' => $tax_query,
);

逻辑说明

  1. 通过meta_query同时匹配有价格和无价格的两类产品,避免未设置价格的产品被默认排除
  2. 排序时先按has_price字段降序,所有存在价格的产品会排在未设置价格的产品之前
  3. 有价格的产品内部再按_price数值升序排列,符合从低到高的排序需求

如果你的场景中存在「价格元键存在但值为空/0」的产品也需要放到末尾,只需要把has_price的条件修改为判断价格大于0即可:

'has_price' => array(
    'key'     => '_price',
    'value'   => 0,
    'compare' => '>',
    'type'    => 'NUMERIC'
),

内容的提问来源于stack exchange,提问作者Sally p

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 05:24:03