首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用"woocommerce_new_order“钩子保存订单元

使用"woocommerce_new_order“钩子保存订单元
EN

Stack Overflow用户
提问于 2022-02-16 10:51:34
回答 1查看 474关注 0票数 1

我需要跟踪,如果一个产品是从一个用户从一个特定的网站购买,这就是为什么我需要为订单设置一个元。

让我们专注于这段代码:

代码语言:javascript
运行
复制
add_action( 'woocommerce_new_order', 'add_affilate_meta', 10, 1);

function add_affilate_meta( $order_id ){
   $targetProd = 3115;
   
   // check if product is present
   $order = wc_get_order( $order_id ); 

   $affiliationProduct = false;    
   foreach ($order->get_items() as $item_key => $item ):
     $product_id = $item->get_product_id();

      if($product_id == $targetProd):
        $affiliationProduct = true;
        break;
      endif;
    endforeach;

    // this is just for debug
    update_post_meta( $order_id, 'test_affiliate', $product_id );

    ... some other stuff ...
}

$affiliationProduct,因此,test_affiliate元始终是假/空的。为什么?当然,我相信这篇文章是按顺序排列的。当我试图分析它的内容时,它似乎还没有“准备好”。

我找不到任何其他方法来调试代码,因为我不能在不导致var_dump()错误的情况下什么都不做。

任何帮助都将不胜感激。

EN

回答 1

Stack Overflow用户

发布于 2022-02-16 11:13:47

您确实可以使用woocommerce_new_order钩子,但是代码中缺少的是$order->save();

所以你得到了:

代码语言:javascript
运行
复制
function action_woocommerce_new_order( $order_id ) {
    // Get the WC_Order Object
    $order = wc_get_order( $order_id );

    // Setting
    $target_prod = 30;

    // Initialize
    $affiliation_product = false;
    $product_id = 0;
   
    // Loop trough
    foreach ( $order->get_items() as $item_key => $item ) {
        // Get 
        $product_id = $item->get_product_id();

        // Compare
        if ( $product_id == $target_prod ) {
            $affiliation_product = true;
            break;
        }
    }
    
    // Update meta data         
    $order->update_meta_data( 'test_affiliate', $product_id );
    
    // Save
    $order->save();
        
    // When true
    if ( $affiliation_product ) {
        // Do something
    }
}
add_action( 'woocommerce_new_order', 'action_woocommerce_new_order', 10, 1 );
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71140449

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档