Search code examples
phpwordpresswoocommercepaymentorders

Add custom meta data after Payment confirmation in WooCommerce


I was looking around the web for a solution to add the response from the payment gateway I am using.

I would like to add the verification code I get and some more data. I need to add this once the payment is complete.

// Payment complete
$order->payment_complete($payment_id);

I did try this code but does not work for me:

   add_action('woocommerce_checkout_update_order_meta', 
        'my_custom_checkout_field_update_order_meta');

    function my_custom_checkout_field_update_order_meta( $order_id ) {
         update_post_meta( $order_id, 'My Field', 'test');
    }

Any help will be appreciated


Solution

  • You should better use dedicated woocommerce_payment_complete action hook this way:

    add_action('woocommerce_payment_complete', 'custom_update_order_meta', 20, 1 );
    function custom_update_order_meta( $order_id ) {
         update_post_meta( $order_id, 'My Field', 'test');
    }
    

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

    This should works.


    For A plugin you will need to add this first in the __construct() function:

    add_action('woocommerce_payment_complete', array( $this 'custom_update_order_meta'), 20, 1 );
    

    And then something like:

    public function custom_update_order_meta( $order_id ) {
         update_post_meta( $order_id, 'My Field', 'test');
    }