在 WooCommerce 中,我想在客户成功结帐后向 API 发送请求。它基本上是一个客户销售在线类(class)的网站(例如 udemy )。
当客户结帐时,我想发送 API 请求并为用户注册该特定类(class)。我尝试了几个 WooCommerce Hook ,但没有一个对我有用。
这是我正在使用的代码:
add_action('woocommerce_checkout_order_processed', 'enroll_student', 10, 1);
function enroll_student($order_id)
{
echo $order_id;
echo "Hooked";
}
我正在为插件编写此代码,为了使其更容易,我目前使用货到付款方法。
任何人都可以指出我哪里出了问题,因为当我结账时,我看不到我正在打印的“hooked”消息,也看不到 $order_id
?
它带我到成功页面,但没有显示我正在打印的这两件事。
最佳答案
Update 2 Only For Woocommerce 3+ (added restriction to execute the code only once)
add_action('woocommerce_thankyou', 'enroll_student', 10, 1);
function enroll_student( $order_id ) {
if ( ! $order_id )
return;
// Allow code execution only once
if( ! get_post_meta( $order_id, '_thankyou_action_done', true ) ) {
// Get an instance of the WC_Order object
$order = wc_get_order( $order_id );
// Get the order key
$order_key = $order->get_order_key();
// Get the order number
$order_key = $order->get_order_number();
if($order->is_paid())
$paid = __('yes');
else
$paid = __('no');
// Loop through order items
foreach ( $order->get_items() as $item_id => $item ) {
// Get the product object
$product = $item->get_product();
// Get the product Id
$product_id = $product->get_id();
// Get the product name
$product_id = $item->get_name();
}
// Output some data
echo '<p>Order ID: '. $order_id . ' — Order Status: ' . $order->get_status() . ' — Order is paid: ' . $paid . '</p>';
// Flag the action as done (to avoid repetitions on reload for example)
$order->update_meta_data( '_thankyou_action_done', true );
$order->save();
}
}
代码位于事件子主题(或主题)的 function.php 文件中或任何插件文件中。
相关主题:
代码已经过测试并且可以工作。
<小时/>Updated (to get the product Id from Orders items as asked in your comment)
也许您可以使用 woocommerce_thankyou
Hook ,它将在收到订单的页面上显示您的回显代码,如下所示:
add_action('woocommerce_thankyou', 'enroll_student', 10, 1);
function enroll_student( $order_id ) {
if ( ! $order_id )
return;
// 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>';
}
代码位于事件子主题(或主题)的 function.php 文件中或任何插件文件中。
代码已经过测试并且可以工作。
Then you can use all class
WC_Abstract_Order
methods on the$order
object.
相关:
关于php - 成功结帐钩子(Hook)后获取订单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42530626/