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

合并多维数组同taxonomy子数组 适配Wordpress自定义文章类型查询

WordPress tax_query相同分类法条件合并方案

问题原因

你当前的写法会让WordPress判定为「内容需同时属于merk分类下的coral和deluxe两个术语」,自然没有符合要求的查询结果。同分类法的多值筛选需要把所有选中的术语合并到同一个terms数组中,才能实现「满足任意一个术语即可」的筛选逻辑。

实现代码

你可以用下面的通用函数自动合并相同分类法的查询条件:

function merge_duplicate_tax_query_items( $original_query ) {
    // 保留原有的全局关联关系
    $processed_query = [
        'relation' => $original_query['relation'] ?? 'AND'
    ];
    $taxonomy_groups = [];

    foreach ( $original_query as $item ) {
        // 跳过非查询条件的键
        if ( !is_array($item) || empty($item['taxonomy']) ) {
            continue;
        }

        $tax_key = $item['taxonomy'] . '_' . $item['field'];
        if ( !isset($taxonomy_groups[$tax_key]) ) {
            // 首次出现该分类法+匹配字段组合,直接存储
            $taxonomy_groups[$tax_key] = $item;
        } else {
            // 已存在则合并terms数组并去重
            $taxonomy_groups[$tax_key]['terms'] = array_unique(
                array_merge( $taxonomy_groups[$tax_key]['terms'], $item['terms'] )
            );
        }
    }

    // 重新组装为符合WordPress要求的查询结构
    return array_merge( $processed_query, array_values($taxonomy_groups) );
}

使用方法

直接将你生成的原始查询数组传入函数即可得到符合要求的结构:

// 你之前生成的原始查询数组
$original_array = [ 
    'relation' => 'AND',
    [
        'taxonomy' => 'merk',
        'field' => 'slug', 
        'terms' => ['coral']
    ],
    [
        'taxonomy' => 'merk',
        'field' => 'slug', 
        'terms' => ['deluxe']
    ]
];

// 处理后的查询数组可直接传入WP_Query的tax_query参数
$tax_query = merge_duplicate_tax_query_items( $original_array );

补充说明

这里用分类法+匹配字段作为分组键,兼容同个分类法下用不同字段(比如slug、term_id)查询的场景,如果你确定所有查询的field都一致,也可以简化为仅用taxonomy作为分组键。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 15:42:03