如何获得特定类别的“在售”产品数量?

时间:2018-01-24 15:57:16

标签: php wordpress woocommerce php-5.3 woothemes

我是woocommerce 2.8,我如何计算特定类别(例如:电脑)的“特价商店”中存在的产品?

我找到了计算所有产品的方法:

$count_posts = wp_count_posts( 'product' );
return $count_posts->publish;

但是,如何才能获得特定类别的“待售”产品数量?

由于

1 个答案:

答案 0 :(得分:2)

$args = array(
    'post_type'      => 'product',
    'posts_per_page' => -1,
    'tax_query'     => array(
        array(
            'taxonomy'  => 'product_cat',
            'field'     => 'id', 
            'terms'     => here goes your category id, you can also go for slug
        )
    ),
    'meta_query'     => array(
        'relation' => 'OR',
        array(
            'key'           => '_sale_price',
            'value'         => 0,
            'compare'       => '>',
            'type'          => 'numeric'
        ),
        array(
            'key'           => '_min_variation_sale_price',
            'value'         => 0,
            'compare'       => '>',
            'type'          => 'numeric'
        )
    )
);
$query = new WP_Query($args);
$onSaleCount = $query->found_posts;

上面介绍了属于tax_query下提到的类别的简单和可变产品。

我不确定是否有更好的方法,但这应该有效。

LE - 根据评论更改了args以排除缺货产品。

$args = array(
    'post_type' => 'product',
    'posts_per_page' => -1,
    'tax_query' => array(
        array(
            'taxonomy' => 'product_cat',
            'field' => 'id',
            'terms' => here goes your category id, you can also go for slug
        )
    ),
    'meta_query' => array(
        'relation' => 'AND',
        array(
            'relation' => 'OR',
            array(
                'key' => '_sale_price',
                'value' => 0,
                'compare' => '>',
                'type' => 'numeric'
            ),
            array(
                'key' => '_min_variation_sale_price',
                'value' => 0,
                'compare' => '>',
                'type' => 'numeric'
            )
        ),
        array(
            'key' => '_stock_status',
            'value' => 'instock'
        ),
    )
);