而不是“woocommerce_thankyou”钩子,“woocommerce_checkout_order_processed”钩子是相关的钩子。“woocommerce_checkout_order_processed”钩子只会被调用一次,你不需要为每个产品添加meta并进行额外的调用来保持检查代码只运行一次。因为,“woocommerce_thankyou”可以多次调用,每次感谢页面加载时。替换为add_action('woocommerce_thankyou', 'enroll_student', 10, 1);
add_action('woocommerce_checkout_order_processed', 'enroll_student', 10, 1);
并删除元代码和检查。更新的代码是
add_action('woocommerce_checkout_order_processed', 'enroll_student', 10, 1);
function enroll_student( $order_id ) {
// Getting an instance of the order object
$order = wc_get_order( $order_id );
if($order->is_paid())
$paid = 'yes';
else
$paid = 'no';
// iterating through each order items (getting product ID and the product object)
// (work for simple and variable products)
foreach ( $order->get_items() as $item_id => $item ) {
if( $item['variation_id'] > 0 ){
$product_id = $item['variation_id']; // variable product
} else {
$product_id = $item['product_id']; // simple product
}
// Get the product object
$product = wc_get_product( $product_id );
}
// Ouptput some data
echo '<p>Order ID: '. $order_id . ' — Order Status: ' . $order->get_status() . ' — Order is paid: ' . $paid . '</p>';
}