phpwordpresswoocommerceordersmollie

Update WooCommerce order custom metadata based on Mollie payment status


In WooCommerce, I'm using Mollie to get payments online. I tried to come up with the below code to update a custom order field depending on the status of the order payment, but it's not working.

Any help to fix this code please ?

add_action( 'woocommerce_checkout_update_order_meta', 'update_custom_is_order_paid_field' );

function update_custom_is_order_paid_field( $order_id ) {
    
    // Get the order object
    $order = wc_get_order( $order_id );

    // Get the payment method
    $mollie_paid_and_processed = $order->get_mollie_paid_and_processed();

    // Set the custom_is_order_paid field based on the value of '_mollie_paid_and_processed'
    if ( $mollie_paid_and_processed == '1' ) {
        update_post_meta( $order_id, 'custom_is_order_paid', '1' );
        
    } elseif ( $mollie_paid_and_processed == '0' ) {
        update_post_meta( $order_id, 'custom_is_order_paid', '0' );
        
    } else {
        
    }
}

Solution

  • You should try to use the following simplified code, that is triggered on order status change (compatible with High Performance Order Storage):

    add_action( 'woocommerce_order_status_changed', 'update_custom_order_meta_conditionally', 10, 4);
    function update_custom_order_meta_conditionally( $order_id, $from_status, $to_status, $order ) {
        $order->update_meta_data( 'custom_is_order_paid', ( $order->get_mollie_paid_and_processed() ? '1' : '0' ) );
        $order->save();
    }
    

    Code goes in functions.php file of your child theme (or in a plugin). It should better work.


    Important note:

    Since version 3, WooCommerce has migrated progressively to custom Database tables, then you should not use anymore, WordPress post meta functions and instead use WC_Data CRUD methods on the WC_Order object.

    You should not use anymore woocommerce_checkout_update_order_meta action hook, replaced with: