I am using the following args to search WooCommerce products in the title or the SKU.
The search should do a partial match on the search term e.g.‘timb’ would match ‘Timber chair’ in the title or ‘M-TIMB’ in the SKU.
I am trying the below but it seems to search for products that have the search term in both the title and SKU
What is the correct $args to search for a partial match in the SKU or title?
// Query products matching the search string in their SKU or title
$args = [
'post_type' => 'product', // Search in 'product' post type
'post_status' => 'publish', // Only published products
'posts_per_page' => 20, // Limit results to 20 per page
's' => $search, // Search term in title and content
'meta_query' => [
'relation' => 'OR', // Either SKU or title
[
'key' => '_sku',
'value' => $search,
'compare' => 'LIKE' // Partial match on SKU
]
],
'fields' => 'ids' // Only get post IDs to optimize performance
];
Note this searches the title correctly:
$args = [
'post_type' => 'product',
'post_status' => 'publish',
's' => $search, // Search term
'posts_per_page' => 20, // Adjust if you need to limit results
];
And this searches the SKU correctly:
$args = [
'post_type' => 'product', // Search in 'product' post type
'post_status' => 'publish', // Only published products
'posts_per_page' => 20, // Limit results to 20 per page
'meta_query' => [ // Custom fields query (e.g., SKU)
[
'key' => '_sku',
'value' => $search,
'compare' => 'LIKE' // Partial match on SKU
]
],
'fields' => 'ids'
];
If I combine the two as separate calls I get the answer I want but I want to do it with one call.
Based on the comment below I have modified args to:
$args = [
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => 20,
'title_filter' => $search, // new
'title_filter_relation' => 'OR', // new
'meta_query' => [
'relation' => 'OR',
[
'key' => '_sku',
'value' => $search,
'compare' => 'LIKE'
]
],
'fields' => 'ids'
];
but it still returns and AND match