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

解决WP_Query中orderby='date'无效 实现WooCommerce产品评论按日期排序

WooCommerce产品评论按日期排序不生效解决方案

核心错误原因

你设置的orderby参数不生效,是因为WP_Query是WordPress用于查询文章/自定义文章类型的接口,无法直接查询评论数据,WooCommerce的产品评论属于原生comment数据类型,需要使用专用的WP_Comment_Query接口查询。

正确查询代码(按评论日期排序)

如果你是要获取指定产品的评论列表并按日期排序,使用如下代码即可:

// 评论查询参数配置
$comment_args = [
    'post_type'   => 'product', // 限定仅查询WooCommerce产品对应的评论
    'post_id'     => 123, // 替换为你要查询的目标产品ID,产品详情页可直接传get_the_ID()
    'status'      => 'approve', // 仅返回已审核通过的公开评论
    'orderby'     => 'date',
    'order'       => 'DESC', // 最新评论在前,需要旧评论在前改为ASC即可
    'number'      => 20, // 单页返回评论数量
];

// 执行查询
$comment_query = new WP_Comment_Query();
$product_comments = $comment_query->query($comment_args);

// 遍历输出评论
if (!empty($product_comments)) {
    foreach ($product_comments as $single_comment) {
        // 输出评论内容、作者、时间等信息示例
        echo '<div class="review-item">';
        echo '<h4>' . esc_html($single_comment->comment_author) . '</h4>';
        echo '<p>' . esc_html($single_comment->comment_content) . '</p>';
        echo '<span>' . esc_html($single_comment->comment_date) . '</span>';
        echo '</div>';
    }
}

特殊场景:WP_Query查询产品时按评论日期排序

如果你是要查询产品列表,按产品最新评论的日期排序,才需要使用WP_Query,此时需要修改orderby参数值为comment_date,而非date(date对应产品本身的发布时间),示例代码如下:

$product_args = [
    'post_type'      => 'product',
    'posts_per_page' => 10,
    'orderby'        => 'comment_date', // 按评论日期排序
    'order'          => 'DESC',
    'post_status'    => 'publish',
];
$product_query = new WP_Query($product_args);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 00:36:03