繁体   English   中英

将两个单独的 wp 查询合并为一个查询以进行搜索

[英]Combine two separate wp queries into one single query for search

我目前在我的类别页面上有一个搜索栏,可以搜索产品标题(自定义帖子类型)或品牌分类。 我可以让这两个独立工作,将 arguments 传递给 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()) :

以此类推; 那么合并 arguments 缺少什么?

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

您可以像这样组合查询。 您可以添加多个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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM