WordPress query through Products variation stock [closed]
IT Nursery
May 28, 2022
0
I have WooCommerce variable products and a filter which is filtering products based on variation attributes.
I have variation attribute depth which has numeric value (from 1 to 20) and the filter is working fine. But I want to display In Stock variations only
On the other hand it is displaying all products including out of stock selected depth value (variation). So I want to hide product which will have selected depth value but no stock.
(Note to other readers: The question author and I have already discussed via chat, so I’m going straight to the code.)
I think for performance reason, you should do it this way:
// FIRST PART: Get the variations which are in stock.
$paged = max( 1, get_query_var( 'paged' ) );
$wccaf_depth = array( '19', '1' ); // example
$args = array(
'post_type' => 'product_variation',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => '_stock_status',
'value' => 'instock',
'compare' => '=',
),
array(
'key' => 'attribute_pa_tread-depth',
'value' => $wccaf_depth,
'compare' => 'IN',
),
),
'fields' => 'id=>parent',
'paged' => $paged,
'posts_per_page' => 1, // example
'groupby' => 'post_parent', // *this is a custom query arg
);
$q = new WP_Query( $args );
$parent_ids = wp_list_pluck( $q->posts, 'post_parent' );
// SECOND PART: Get the parent products. Here you don't need the above
// meta_query, but you can of course make other meta queries.
$args = array(
'post_type' => 'product',
'post__in' => $parent_ids,
);
$loop = new WP_Query( $args );
// Run your loop here.
// Paginate the first part.
echo paginate_links( array(
'total' => $q->max_num_pages,
'current' => $paged,
//...
) );
And be sure to add this filter to your functions file:
add_filter( 'posts_groupby', 'custom_posts_groupby', 10, 2 );
function custom_posts_groupby( $groupby, $query ) {
if ( 'post_parent' === $query->get( 'groupby' ) ) {
global $wpdb;
return "$wpdb->posts.post_parent";
}
return $groupby;
}
However, if this approach (where we paginate the first part) doesn’t work for you, let me know. But you can actually always view the answer’s revisions..