仅显示带有WP_Query

时间:2019-05-14 20:10:45

标签: php wordpress woocommerce product stock

我有这段代码,它显示出最佳的销售量,但同时也显示了没有库存的产品,我该如何修改代码。以便只显示有库存的产品? 。谢谢!

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

2 个答案:

答案 0 :(得分:2)

您可以添加库存元值参数:

chr()

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

祝你好运!

答案 1 :(得分:1)

从WooCommerce 3开始,有两种方法可以排除WP_Query上的“缺货”产品:

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

$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' => '!=',
    ) ),
) );

两种方法都可以。