Home  >  Q&A  >  body text

Add all order item SKUs to order number in Woocommerce

I have this code that adds the product name as a prefix to the order number via functions.php, but I want to change it to add the SKU. Also, it would be nice if the quantity for each SKU could be inserted at the same time.

Similar to: 2xSKUA_1xSKUB_Order number

Can anyone point me in the right direction?

function filter_woocommerce_order_number( $this_get_id, $instance ) { 
    $order = new WC_Order( $this_get_id );
    $items = $order->get_items();
    foreach ( $items as $item ) {
        $product_name = preg_replace('/\s+/', '_', $item['name']);;
        break;
    }
    $new_id = $product_name.'_'.$this_get_id;

    return $new_id; 
}; 
add_filter( 'woocommerce_order_number', 'filter_woocommerce_order_number', 10, 2 );

P粉707235568P粉707235568427 days ago565

reply all(1)I'll reply

  • P粉949848849

    P粉9498488492023-09-12 17:26:24

    To add SKU before the quantity of the order items (products), use it after the order number. Code revisited below:

    add_filter( 'woocommerce_order_number', 'filter_woocommerce_order_number', 10, 2 );
    function filter_woocommerce_order_number( $order_number, $order ) {
        $prefix = array(); // Initializing
    
        // Loop through order items
        foreach ( $order->get_items() as $item ) {
            $product  = $item->get_product(); // Get the product object
    
            // Add the quantity with the sku to the array
            $prefix[] = $item->get_quantity() . 'X' . $product->get_sku(); 
        }
        // return everything merged in a string
        return implode('_', $prefix) . '_' . $order_number;
    }
    

    It should work as you expect.

    reply
    0
  • Cancelreply