Alessandro Bergagna
Alessandro Bergagna

Reputation: 33

Create a WooCommerce order custom field with a value based on specific property

I would like to ask you for help to create a custom field.

How to create, without a plugin, a custom field "frontier_agent" for WooCommerce orders based on created_via property as follows:

Any help is appreciated.

Upvotes: 1

Views: 741

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253968

The following that will create a frontier_agent custom field based on create_via order property:

add_action( 'woocommerce_order_status_changed', 'create_frontier_agent_order_custom_field', 10, 4 );
function create_frontier_agent_order_custom_field( $order_id, $old_status, $new_status, $order ) {
    if( ! $order->get_meta('frontier_agent') ) {
        if( $order->get_created_via() === 'checkout' ) {
            $value = '7500';
        } elseif( $order->get_created_via() === 'amazon' ) {
            $value = '7000';
        }
        
        if( isset($value) ) {
            $order->update_meta_data('frontier_agent', $value);
            $order->save();
        }
    }
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

Upvotes: 2

Related Questions