Home > Enterprise >  Add a prefix only to an future upcoming order number in WooCommerce
Add a prefix only to an future upcoming order number in WooCommerce

Time:10-09

How can i add a prefix to all future order numbers in WooCommerce? I am currently using the following snippet:

add_filter( 'woocommerce_order_number', 'change_woocommerce_order_number' );
function change_woocommerce_order_number( $order_id ) {
    $prefix = 'MTN-';
    $new_order_id = $prefix . $order_id . $suffix;
    return $new_order_id;
}

But it's also add prefix to all existing order numbers. Any advice?

CodePudding user response:

First you can use the woocommerce_checkout_create_order action hook to add custom meta data for new orders:

function action_woocommerce_checkout_create_order( $order, $data ) {
    // Settings
    $meta_key = '_your_custom_meta_key';
    $value = true;

    // Save
    $order->update_meta_data( $meta_key, $value );
}
add_action( 'woocommerce_checkout_create_order', 'action_woocommerce_checkout_create_order', 10, 2 );

Subsequently, the prefix will only be added to orders for which the meta data is available:

function filter_woocommerce_order_number( $order_number, $order ) {
    // Get meta
    $value = $order->get_meta( '_your_custom_meta_key' );

    // Prefix
    $prefix = 'MTN-';

    // When meta NOT empty AND true
    if ( ! empty ( $value ) && $value == true ) {
        // Add prefix
        $order_number = $prefix . $order_number;
    }

    return $order_number;
}
add_filter( 'woocommerce_order_number', 'filter_woocommerce_order_number', 10, 2 );
  • Related