dtg7662 2018-01-31 17:17
浏览 268
已采纳

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

When the user buy a product, I want to save a series of data in custom tables in database. This data will be the product id, custom fields I have, and some other data.

My idea is that this should be done when the payment of the product has been made correctly, that is to say, at the time of payment.

I wanted you to give me advice, I have created a way but I don't know if it is the right one or if you would recommend any other way.

I've edited the thankyou page, and I have inserted this code:

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

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

1条回答 默认 最新

  • douan9541 2018-01-31 18:06
    关注

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

    The correct hook to be used that you can find inside WC_Order payment_complete() method is woocommerce_payment_complete. So your code should be for most payment gateways:

    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*/);
    }
    

    Code goes in function.php file of the active child theme (or active theme).


    For payment methods (CHEQUE HERE) as 'cheque', 'bacs' and 'cod' that needs to be "completed" by shop manager, you will use instead:

    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*/);
    }
    

    So when order status will change to completed for this specific payment methods, this hook will be triggered…

    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

    Code goes in function.php file of the active child theme (or active theme).

    This should works.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?