I am trying to find products that are on sale (including product variations) in addition to another meta_query of price under X.
The wc_get_product_ids_on_sale()
function will return the IDs of products (including variations) that are on sale. Therefore I added this to post__in
.
$query_args['post__in'] = wc_get_product_ids_on_sale();
However, this will override my second part of the query which is to find products under £X
$query_args = array(
'relation' => 'AND',
'price' => array(
'key' => '_price',
'value' => 15,
'compare' => '<',
'type' => 'numeric'
),
'stock_status' => array(
'key' => '_stock_status',
'value' => 'instock',
'compare' => '=',
),
);
return $query_args;
$args = array(
'post_type' => array('product', 'product_variation'),
'post__not_in' => array( $product_id ),
'posts_per_page' => 12,
'return' => 'ids',
'post__in' => wc_get_product_ids_on_sale(),
'meta_query' => $meta_query; // this contains the price under X query
);
I believe post__in
is telling WP_Query to only return those posts regardless of any other query.
Are there appropriate methods to do these queries separately and combine them in some way?
2
Answers
Add below code snippet for price_and_stock combination query.
More details on the custom query can be found here
== Alternate ==
Note: you cannot combine
post__in
andpost__not_in
in the same query.post__in
andpost__not_in
are mutually exclusive.Conflict does not happen because of the combination of
meta_query
andpost__in
, it happens becausepost__not_in
andpost__in
can’t work in the same query. Source: https://developer.wordpress.org/reference/classes/wp_query/#post-page-parametersIf you wish to search through products on sale together with excluding one product in the same query, you can try
array_diff
them together and add them topost__in
only.Example:
This way your are telling your query to search through products that are on sale, excluding the one with
$product_id
.Just make sure your
wc_
function always returns an array or else this could fail.