John Davidson

php - Combine two separate wp queries into one single query for search

0 comments
Message:


I currently have a search bar on my category page which will allow the search of either the product title (custom post type) or a taxonomy of brand. I can get both of these to work independently, passing in either arguments to the WP_Query, however if I attempt to array merge them both together, neither work.


What I have is:


$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()) :


And so on with the loop; So what am I missing with the merge arguments?


Essentially i am using 's' => $search only in one of the arrays to search the post name, which I do not need (or believe i need) in the brands taxonomy array



My Answer:
array(
'taxonomy' => 'brand',
'field' => 'name',
'terms' => $search
),
array(
'post_type' => 'product',
's' => $search
)
);

$query = new WP_Query($cats);

This code combines both the taxonomy and post type queries into one single query. The 's' parameter is used to search for the product title, while the 'taxonomy' parameter is used to search for the brand taxonomy. This way, you can search for both the product title and brand taxonomy in one single query.

Rate this post

3 of 5 based on 3625 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us