获取给定产品的总订单量

Get the total amount of orders for a given product

我正在使用 WooCommerce,并且一直在使用此代码:

$units_sold = get_post_meta( get_the_ID(), 'total_sales', true );

此元 returns 已售出的商品数量。因此,如果有人购买两件商品,那么,它 returns 两件。我想获得一种产品的订单数量,而不是售出的数量。

你知道我怎样才能轻松有效地得到这个号码吗?

谢谢

这是一个自定义函数,它将 return 一个产品的订单数量。你有一个 $product_id 作为参数:

function get_orders_count_for_a_product( $product_id ){

    $orders = wc_get_orders( array(
        'numberposts' => -1,
        'post_type' => 'shop_order',
        'post_status' => array('wc-completed') // completed status only
    ) );

    $count_orders = 0;
    foreach($orders as $order){
        $has_product = false;
        foreach($order->get_items() as $item_values)
            if( $item_values['product_id'] == $product_id )
                $has_product = true;
        if( $has_product )
            $count_orders++;
    }
    return $count_orders;
}

代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件。

USAGE:

// Here Product ID is 125
$the_product_id = 125; 
$number_of orders = get_orders_count_for_a_product($the_product_id);
// Output the value
echo 'Number of orders for product ID ' . $the_product_id . ' is: '. $number_of orders;