Filter WooCommerce products with post__in and additional meta queries



PHP Snippet 1:

$on_sale_product_ids = wc_get_product_ids_on_sale();

$queried_products = wc_get_products(array(
    'limit' => 1000,
    'orderby' => 'id',
    'order' => 'asc',
    'price_and_stock' => true,
));
$on_sale_products = wc_get_products(array('include' => array_values($on_sale_product_ids) , 'limit' => count($on_sale_product_ids)) );

$total_products = array_merge($on_sale_products,$queried_products );

PHP Snippet 2:

function handle_custom_query_var( $query, $query_vars ) {
    if ( ! empty( $query_vars['price_and_stock'] ) ) {
        $query['meta_query'][] =    array( 'relation' => 'AND',
    'price' => array(
        'key' => '_price',
        'value' => 9,
        'compare' => '<',
        'type' => 'numeric'
    ),
    'stock_status' => array(
        'key' => '_stock_status',
        'value' => 'instock',
        'compare' => '=',
    )
            );
    }

    return $query;
}
add_filter( 'woocommerce_product_data_store_cpt_get_products_query', 'handle_custom_query_var', 10, 2 );

PHP Snippet 3:

$meta_query = array(
                'relation' => 'AND',
                'price' => array(
                    'key' => '_price',
                    'value' => 9,
                    'compare' => '<',
                    'type' => 'numeric'
                ),
                'stock_status' => array(
                    'key' => '_stock_status',
                    'value' => 'instock',
                    'compare' => '=',
                ),
            );
        
            $args = array(
                'post_type' => array('product', 'product_variation'),
                'posts_per_page' => 1000,
                'return' => 'ids',
                'post__in' => wc_get_product_ids_on_sale(),
                'meta_query' => $meta_query // this contains the price under X query
            );
            $total_products = wc_get_products($args);

PHP Snippet 4:

$args = array(
    'post_type' => array('product', 'product_variation'),
    'posts_per_page' => 12,
    'return' => 'ids',
    'post__in' => array_diff(wc_get_product_ids_on_sale(), [ $product_id ]),
    'meta_query' => $meta_query; // this contains the price under X query
);