i have this code that prefixes the product name into the order number through functions.php but i want to change it to add the SKU instead. Also it would be good, if the quantity of each SKU would be inserted as well.
Something like: 2xSKUA_1xSKUB_Ordernumber
Can someone 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 );
To prefix order items (product) quantity with the SKU, to the order number, use the. following revisited code:
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.