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

WooCommerce自定义商品排序功能导致WordPress后台文章页面丢失如何修复

问题根源

你使用的代码未限制生效范围,posts_clauses 是全局过滤器,会作用于WordPress所有文章查询请求,包括后台的文章、页面查询。后台查询非商品类型内容时,代码追加的分类法过滤条件会错误过滤正常的文章、页面数据,导致列表为空。

修复后的完整代码
add_filter('posts_clauses', 'posts_clauses_with_tax', 10, 2);
function posts_clauses_with_tax( $clauses, $wp_query ) {
    // 仅前台商品主查询才执行排序逻辑,其余场景直接返回原查询
    if ( is_admin() || !$wp_query->is_main_query() || $wp_query->get('post_type') !== 'product' ) {
        return $clauses;
    }

    global $wpdb;
    $taxonomies = array('pwb-brand');
    $orderBy['field'] = "pwb-brand";
    $orderBy['direction'] = "ASC";

    if( in_array($orderBy['field'], $taxonomies) ) {
        $clauses['join'] .= "
            LEFT OUTER JOIN {$wpdb->term_relationships} AS rel2 ON {$wpdb->posts}.ID = rel2.object_id
            LEFT OUTER JOIN {$wpdb->term_taxonomy} AS tax2 ON rel2.term_taxonomy_id = tax2.term_taxonomy_id
            LEFT OUTER JOIN {$wpdb->terms} USING (term_id)
        ";
        
        $clauses['where'] .= " AND (taxonomy = '".$orderBy['field']."' OR taxonomy IS NULL)";
        $clauses['groupby'] = "rel2.object_id";
        $clauses['orderby']  = "GROUP_CONCAT({$wpdb->terms}.slug ORDER BY slug ASC) ";
      
        $clauses['orderby'] .= ", {$wpdb->posts}.post_title ASC"; 
        return $clauses;
    }
    return $clauses;
}
调整说明
  • 新增后台请求拦截:后台访问时直接返回原始查询逻辑,完全不影响后台所有内容的查询
  • 新增主查询判断:仅作用于页面主查询,不会干扰侧边栏、相关商品推荐等自定义小查询
  • 新增文章类型限制:仅对WooCommerce的product商品类型查询生效,不会影响文章、页面、其他自定义文章类型的正常加载

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 16:06:08