1
votes

I am going to write a query for woocommerce products to show products that have stock = 1. also if a product is variable and any variables has stock =1 should include in this query. for example:

Product one:

  • simple
  • stock quantity: 1

Product two:

  • simple
  • stock quantity: 5

Product three:

  • variation
  • variable one:
  • stock quantity: 1
  • variable two:
  • stock quantity: 4
  • variable three:
  • stock quantity: 7

Product four:

  • variation
  • variable one:
  • stock quantity: 3
  • variable two:
  • stock quantity: 2
  • variable three:
  • stock quantity: 5

so the query should return product one and product 3.

I used the below query:

$query = array(
        'relation' => 'AND',
        array(
            'key'     => '_stock_status',
            'value'   => 'instock',
            'compare' => '='
        ),
        array(
            'key'     => '_stock',
            'type'    => 'numeric',
            'value'   => '1',
            'compare' => '='
        ),
    ); 

But, It won't work return product three. would you please help me?

thanks in advance.

1

1 Answers

1
votes

you need to include post type product_variation for variation product & product so you can filter the variable product too.

so you can do the following:

add_action( 'woocommerce_product_query', 'modify_query', 10, 2 );

function modify_query( $q, $instance ) {

    $post_type = array( 'product', 'product_variation' );

    $q->set( 'post_type', (array) $post_type );
    $meta_query[] = [
        'relation' => 'AND',
        [
            'key'     => '_stock_status',
            'value'   => 'instock',
            'compare' => '=',
        ],
        [
            'key'     => '_stock',
            'type'    => 'numeric',
            'value'   => '1',
            'compare' => '=',
        ],

    ];

    $q->set( 'meta_query', $meta_query );
}