2

I have this code, it shows the best sales, but it also shows the product without stock, how do I modify the code. so that it only shows the products with stock? . Thanks !

$best_sellers_args = array(

    'post_type' => 'product', 

    'meta_key' => 'total_sales',        

    'posts_per_page' => 6,

    'orderby' =>'meta_value_num',

    'order' => 'DESC'

);

$products = new WP_Query( $best_sellers_args );
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Ulysses
  • 55
  • 1
  • 2
  • 8

2 Answers2

3

Since WooCommerce 3, there is 2 ways to exclude "Out of stock" products on your WP_Query:

1) Including a Tax query like:

$products = new WP_Query( array(
    'post_type' => 'product',
    'meta_key' => 'total_sales',
    'posts_per_page' => 6,
    'orderby' =>'meta_value_num',
    'order' => 'DESC',
    'tax_query' => array( array(
        'taxonomy' => 'product_visibility',
        'field'    => 'name',
        'terms'    => array('outofstock'),
        'operator' => 'NOT IN'
    ) ),
) );

2) Including a Meta query like:

$products = new WP_Query( array(
    'post_type' => 'product',
    'meta_key' => 'total_sales',
    'posts_per_page' => 6,
    'orderby' =>'meta_value_num',
    'order' => 'DESC',
    'meta_query' => array( array(
        'key'     => '_stock_status',
        'value'   => 'outofstock',
        'compare' => '!=',
    ) ),
) );

Both ways work.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
2

You can add the in stock meta value param:

$best_sellers_args = array(

'post_type' => 'product', 

'meta_key' => 'total_sales',        

'posts_per_page' => 6,

'orderby' =>'meta_value_num',

'order' => 'DESC',

'meta_query' => array(
        array(
            'key' => '_stock_status',
            'value' => 'instock'
        )
    )
);

See this blog post for further details: https://www.gavick.com/blog/wp_query-woocommerce-products

Good luck!

Sam Kool
  • 346
  • 2
  • 8