【问题标题】:Do something for each order item based on quantity purchased in WooCommerce根据在 WooCommerce 中购买的数量为每个订单项目做一些事情
【发布时间】:2020-11-04 15:43:58
【问题描述】:

我正在使用 PHP Post 为用户购买的每种产品创建一个具有不同 API 的帐户。

我当前的代码如下所示:

add_action( 'woocommerce_thankyou', 'create_account' );
function create_account( $order_id ){
 $order = wc_get_order( $order_id );
 $items = $order->get_items(); 
 foreach ( $items as $item_id => $item ) {
   $product_id = $item->get_variation_id() ? $item->get_variation_id() : $item->get_product_id();
   if ( $product_id === xxx) {
       //do something
   }
   if ( $product_id === yyy) {
       //do something else
   }
}

现在如果购买了产品 xxx 和 yyy,函数会正确循环它们并创建 2 个帐户。

但这是我的问题:
现在它只为xxx创建一个帐户,为yyy创建一个帐户,无论购买多少。
如果我购买“xxx”5 次(数量 5)和“yyy”3 次(数量 3),我希望创建 8 (5 + 3) 个个人帐户.我以为 foreach 循环会这样做,但它似乎没有考虑订单商品的数量。

我如何处理订单项目数量并为每个产品单元做一些事情?

【问题讨论】:

  • 为什么你不简单地定义一个$sum$count 变量并在foreach 中添加每个值来实现你想要的?
  • 感谢您的回复。我不知道如何在这个函数中使用这些变量

标签: php wordpress woocommerce orders product-quantity


【解决方案1】:

使用基于订单商品数量的FOR循环来处理基于数量的事件:

add_action( 'woocommerce_thankyou', 'create_account' );
function create_account( $order_id ){
    $order = wc_get_order( $order_id );

    foreach ( $order->get_items() as $item ) {
        $product_ids = array($item->get_product_id(), $item->get_variation_id());
        
        $product_id1 = 153; // <== Here define the 'xxx' product id
        $product_id2 = 228; // <== Here define the 'yyy' product id
        
        $quantity = $item->get_quantity();
        
        if ( in_array( $product_id1, $product_ids ) ) {
            for ( $i = 1; $i <= $quantity; $i++ ) {
                // do something
            }
        } 
        elseif ( in_array( $product_id2, $product_ids ) ) {
            for ( $i = 1; $i <= $quantity; $i++ ) {
                // do something else
            }
        }
    }
}

它应该可以工作。

【讨论】:

  • 简洁,易于理解,完全符合我的要求。非常感谢!
猜你喜欢
  • 2021-05-03
  • 2021-04-16
  • 1970-01-01
  • 1970-01-01
  • 2015-10-20
  • 1970-01-01
  • 1970-01-01
  • 2017-09-17
  • 2018-06-18
相关资源
最近更新 更多