问题
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 );
回答1:
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.
回答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!
来源:https://stackoverflow.com/questions/56137935/show-only-woocommerce-in-stock-products-with-a-wp-query