skip to Main Content

I use the following code to modify the order number in WooCommerce.

add_filter( 'woocommerce_order_number', 'change_woocommerce_order_number', 1, 2);

function change_woocommerce_order_number( $order_id, $order ) {
    $prefix = '160-';
    // you will need to get your city as a variable to pass in to priffix 
    $order = wc_get_order( $order_id );
    $order_date = $order->get_date_created();
    $date_created = $order_date->date( 'Ymd' );
    
   
    // You can use either one of $order->id (or) $order_id
    // Both will wor
    return $prefix . $order->id . '-'.$date_created;
}   

This code works during the checkout process but I get an error like this when i manually create an order in WooCommerce backend.

enter image description here

How can I prevent this?

2

Answers


  1. Try this code.

    Replace this lines.

     $order_date = $order->get_date_created();
     $date_created = $order_date->date( 'Ymd' );
    

    To

    $date_created = $order->get_date_created()->date('Ymd');
    
    Login or Signup to reply.
  2. Your code contains some mistakes

    • The use $order = wc_get_order( $order_id );is not necessary, as $order already passed to the function
    • $order->id has been replaced since WooCommerce 3 (2017) with $order->get_id()
    • However, using/replacing $order->get_id() is not needed in this answer, as this is also passed to the function
    • The error will not occur when you place an order, but will occur when you want to create a new order in the backend (which is the case for you). Simply because the order has yet to be created, and that value does not yet exist

    So you get

    function filter_woocommerce_order_number( $order_number, $order ) { 
        // Prefix
        $prefix = '160-';
        
        // Is null
        if ( is_null( $order->get_date_created() ) ) {
            $order->set_date_created( new WC_DateTime() );
        }
        
        // Get date created
        $date_created = $order->get_date_created()->date( 'Ymd' );
    
        return $prefix . $order_number . '-' . $date_created;
    }
    add_filter( 'woocommerce_order_number', 'filter_woocommerce_order_number', 10, 2 );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search