WooCommerce conditional meta query
-
17-12-2020 - |
Pergunta
For this question, I know how to solve it but I am hoping there is a better / faster way to solve it.
I have a custom meta query in my product loop that doesn't display my product if the stock is 0, but I only want to do this when backorder is set to no on a product. Is this possible without running 2 queries (one that gets all the posts and checks if backorders are enabled, and one that only executes the meta query if backorders are not enabled)?
Here is my custom meta query in my functions.php
:
add_action( 'woocommerce_product_query', 'woo_custom_outofstock_query' );
function woo_custom_outofstock_query( $q ) {
$meta_query = $q->get( 'meta_query' );
$meta_query[] = array(
'key' => '_stock',
'value' => '0.000000',
'compare' => 'NOT IN'
);
$q->set( 'meta_query', $meta_query );
}
EDIT: I changed the query to:
$meta_query = $q->get( 'meta_query' );
$meta_query[] = array(
'key' => '_stock',
'value' => '0.000000',
'compare' => 'NOT IN'
);
$meta_query[] = array(
'key' => '_backorders',
'value' => 'no',
'compare' => '!='
);
$q->set( 'meta_query', $meta_query );
This should do the trick but for some reason it is still not working. Also, when I hide out of stock products in the WooCommerce settings, it still doesn't display products with a stock of 0 when backorders are enabled.
Solução
The default relation for a meta query is AND
, so when you have two conditions they will be treated as such:
$meta_query[] = array(
'key' => '_stock',
'value' => '0.000000',
'compare' => 'NOT IN'
);
$meta_query[] = array(
'key' => '_backorders',
'value' => 'no',
'compare' => '!='
);
Get all products with a _stock
meta value NOT IN 0.000000
AND _backorders
NOT EQUAL TO no