仅显示 WP_Query 库存产品中的 WooCommerce

Show only WooCommerce in stock products with a WP_Query

我有这个代码,它显示了最好的销售,但它也显示了没有库存的产品,我该如何修改代码。这样它只显示有库存的产品? .谢谢!

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

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

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

有关详细信息,请参阅此博客 post: https://www.gavick.com/blog/wp_query-woocommerce-products

祝你好运!

从 WooCommerce 3 开始,有 2 种方法可以在您的 WP_Query 上排除 "Out of stock" 产品:

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

两种方式都有效。