在自定义数据库 table 中为 WooCommerce 中的付费订单添加数据

Adding data in a custom database table for paid orders in WooCommerce

当用户购买产品时,我想在数据库中的自定义表中保存一系列数据。此数据将是产品 ID、我拥有的自定义字段和一些其他数据。

我的想法是,这应该在正确完成产品付款时完成,也就是说,在付款时完成。

我希望你能给我建议,我已经创建了一种方法,但我不知道它是否正确,或者你是否会推荐任何其他方法。

我编辑了感谢页面,并插入了这段代码:

$order = new WC_Order ($order->get_id ();
$check_payment = $order->payment_complete ();

if ($check_payment) {
    global $wpdb;
    wpdb->insert (/* CODE DATABASE*/);
} 

As woocommerce Order-received (thankyou) page can be reloaded, it's not really the good way.

您可以在 WC_Order payment_complete() 方法中找到要使用的正确钩子是 woocommerce_payment_complete。所以你的代码应该适用于大多数支付网关:

add_action('woocommerce_payment_complete', 'action_payment_complete', 30, 1 );
function action_payment_complete( $order_id ){
    global $wpdb;

    // Get an instance of the WC_Order object (if needed)
    $order = wc_get_order( $order_id );

    // Your database actions code
    wpdb->insert (/* CODE DATABASE*/);
}

代码进入活动子主题(或活动主题)的 function.php 文件。


对于付款方式 (在此处支票) as 'cheque', 'bacs' 和 'cod' 需要店长"completed",您将改为:

add_action( 'woocommerce_order_status_completed', 'action_order_status_completed', 20, 2 );
function action_payment_complete( $order_id, $order ){
    // The specific payment methods to be target
    $payment_methods = array('bacs','cheque','cod');

    // Only for specific payment methods
    if( ! in_array( $order->get_payment_method(), $payment_methods ) return;

    global $wpdb;

    // Your database actions code
    wpdb->insert (/* CODE DATABASE*/);
}

因此,当此特定付款方式的订单状态更改为已完成时,将触发此挂钩...

You can also use instead woocommerce_order_status_processing if you target Processing order status or woocommerce_order_status_on-hold if you target On Hold order status

代码进入活动子主题(或活动主题)的 function.php 文件。

这应该有效。