我需要跟踪,如果一个产品是从一个用户从一个特定的网站购买,这就是为什么我需要为订单设置一个元。
让我们专注于这段代码:
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()
错误的情况下什么都不做。
任何帮助都将不胜感激。
发布于 2022-02-16 11:13:47
您确实可以使用woocommerce_new_order
钩子,但是代码中缺少的是$order->save();
。
所以你得到了:
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 );
https://stackoverflow.com/questions/71140449
复制相似问题