首页 > 解决方案 > 将两个单独的 wp 查询合并为一个查询以进行搜索

问题描述

我目前在我的类别页面上有一个搜索栏,可以搜索产品标题(自定义帖子类型)或品牌分类。我可以让这两个独立工作,将任一参数传递给 WP_Query,但是如果我尝试将它们合并在一起,则两者都不起作用。

我所拥有的是:

$search = sanitize_text_field($_POST['productsearch']);

$post_category = $_POST['post_cat'];

$cats = array(
    'taxonomy' => 'productscat',
    'field' => 'id',
    'key' => 'name',
    'terms' => $post_category,
);


$args = array(
    'post_type' => 'products', //custom post type
    'post_status' => 'publish',
    'orderby' => 'menu_order',
    'order' => 'ASC',
    's' => $search,
    'tax_query' => $cats,
    'posts_per_page' => -1,
);

$args2 = array(
    'post_type' => 'products', //custom post type
    'post_status' => 'publish',
    'orderby' => 'menu_order',
    'order' => 'ASC',
    'tax_query' => array(
        array(
            'taxonomy' => 'brands',
            'field' => 'slug',
            'terms' => $search,
        ),

    ),
    'posts_per_page' => -1,
);

$merged = array_merge($args, $args2);
$search_query = new WP_Query($merged);


if ($search_query->have_posts()) :

以此类推;那么我在合并参数中缺少什么?

本质上,我's' => $search 只在其中一个数组中使用来搜索帖子名称,我在品牌分类数组中不需要(或相信我需要)

标签: phpwordpress

解决方案


您可以像这样组合查询。您可以添加多个tax_query.

$search = sanitize_text_field($_POST['productsearch']);

$post_category = $_POST['post_cat'];

$args2 = array(
    'post_type'      => 'products', //custom post type
    'post_status'    => 'publish',
    'orderby'        => 'menu_order',
    'order'          => 'ASC',
    's'              => $search,
    'posts_per_page' => -1,
    'tax_query'      => array(
        'relation' => 'OR',
        array(
            'taxonomy' => 'brands',
            'field'    => 'slug',
            'terms'    => $search
        ),
        array(
            'taxonomy' => 'productscat',
            'field'    => 'id',
            'terms'    => $post_category
        )

    )
);

$search_query = new WP_Query( $args2 );

if ( $search_query->have_posts() ) :

endif;

推荐阅读