1

我正在尝试计算订单中有多少具有唯一父产品 ID 的变体。

例如这是我的订单:

Product A: Size: Small, Color: Red
Product A: Size Medium, Color: Blue

Product B: Size: Small, Color: Yellow
Product B: Size: Large, Color Blue

我想计算订单中存在多少唯一产品(在本例中为 2,A 和 B),以及每个唯一产品中存在多少变量(在本例中为每个 2)。

我怎样才能做到这一点?

我用这段代码尝试了一些东西,但我卡住了......

    $order_id       = $order->get_id();
    $order_number   = $order->get_order_number();
    $order_quantity = $order->get_item_count();
    
    # Iterating through each order items (WC_Order_Item_Product objects in WC 3+)
    foreach ( $order_id->get_items() as $item_id => $item_values ) {

    // Product_id
    $product_id = $item_values->get_product_id(); 
    
    // For product variation type
    if( $item_values->is_type('variation') ){
    if( $item_values->get_variation_id() > 0 ){
    for ($x = 0; $x < $item_values->get_variation_id(); $x++) {
        
    }
        // Get the instance of the parent variable product Object
        $parent_product = wc_get_product( $item->get_product_id() );
4

2 回答 2

2

当您有一个作为产品变体的订单项目时,WC_Order_Item_Product方法:

  • get_variation_id()给出变体 ID,一个始终大于零的整数
  • get_product_id()给出父变量产品 ID

要根据需要从代码中获取产品计数,请使用以下内容:

$count_products = array();

foreach ( $order->get_items() as $item ) {
    if ( $item->get_variation_id() > 0 ) {
        if( isset($count[$item->get_product_id()]) {
             $count_products[$item->get_product_id()] += 1;
        } else {
             $count_products[$item->get_product_id()] = 1;
        }
    }
}

echo '<p>Variable products count: ' . count($count_products) . '</p>';

echo '<div>Variations count for each variable product:<br><ul>';
foreach( $count_products as $parent_id => $count ) {
    echo '<li>Variable product Id ' . $parent_id . ' has ' . $count . 'Variation' . _n('', 's', $count) . '</li>';
}
echo '</ul></div>';

现在,如果您想计算数量,您将使用WC_Order_Item_Productmethod get_quantity()

相关:在 WooCommerce 3 中获取订单商品和 WC_Order_Item_Product

于 2021-02-12T09:22:50.763 回答
1

也许这段代码可以帮助你

$order_id       = $order->get_id();
$order_number   = $order->get_order_number();
$order_quantity = $order->get_item_count();
$count=[];
# Iterating through each order items (WC_Order_Item_Product objects in WC 3+)
foreach ( $order->get_items() as $item_id => $item_values ) {
    //$product_name = $item_values->get_name();
    $product_id = $item_values->get_product_id();
    $product_variation_id = $item_values->get_variation_id();
    $count['parent'][$product_id]+= 1;
    if($product_variation_id >0 ){
        $count['child'][$product_id][$product_variation_id] += 1;
    }
}
print_r ($count);

输出 :

[parent] => Array
    [
        [57] => 2
        [56] => 2
    ]

[child] => Array
    [
        [56] => Array
            [
                [61] => 1,
                [68] => 1,
            ],
        [57] => Array
            [
                [82] => 1,
                [89]=> 1,
            ]
    ]

如果您有任何问题,请告诉我;)

于 2021-02-12T07:07:48.257 回答