Show only WooCommerce in stock products with a WP_Query

我的梦境 提交于 2021-01-24 09:26:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!