简体   繁体   English

仅显示带有WP_Query的库存产品中的WooCommerce

[英]Show only WooCommerce in stock products with a WP_Query

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 );

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 有关更多详细信息,请参见此博客文章: https : //www.gavick.com/blog/wp_query-woocommerce-products

Good luck! 祝好运!

Since WooCommerce 3, there is 2 ways to exclude "Out of stock" products on your WP_Query : 从WooCommerce 3开始,有两种方法可以在WP_Query上排除“缺货”产品:

1) Including a Tax query like: 1)包括类似的税查询

$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: 2)包括一个元查询,例如:

$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. 两种方式都可以。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM