1

I'm overriding WooCommerce's default search query to include searching by SKU as well.

// default search query
$query_default_search = new WP_Query(
    array(
        "post_type" => "product",
        "s" => $search_query
    )
);

// SKU query
$query_search_by_sku = new WP_Query(
    array(
        "post_type" => "product",
        "meta_query" => array(
            array(
                "key" => "_sku",
                "value" => $search_query,
                "compare" => "LIKE"
            )
        )
    )
);

If the default search query doesn't return any posts, I assume that an SKU has been entered and I run the SKU query. However, I want to merge both query arguments into one WP_Query call, rather than merging the results of both queries using array_merge. If both queries had meta-query, I could use an OR relation, but this is different.

How can this be done?

2 Answers 2

1

What about this ?

$query_withMeta_search = new WP_Query(
    array(
        "post_type" => "product",
        "s" => $search_query,
        "meta_query" => array(
                "key" => "_sku",
                "value" => $search_query,
                "compare" => "LIKE"
        )
    )
);
2
  • this doesn't work.
    – adi
    Aug 13, 2015 at 14:11
  • Well, it does work. The only problem is that it returns products that have search query in title AND in SKU. And most probably you wanted to get OR instead of AND ;) Feb 15, 2019 at 7:28
1

Create the array you'd like to use in it's entirety before running. Something like

if($search_query) {
     // create the basic query array
} else {
     // create the more advanced query array
}

// then run the query on the one you want
new WP_Query($args);

Hope that helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.