I have a WooCommerce store and everything is working well. But I would like to add a number in front of every item name when an order is placed so I can put numbers on the box so the customer knows which box contains what product.
(I only have 1 product but the custommer can customize that product with a lot of product options)
Example: in the order email, the product name stays the same but an incremental number is placed in front of the name.
- product
- product
- product
I use this code to edit the product name:
add_filter( 'woocommerce_order_item_name', 'change_orders_items_names', 10, 1 ); function change_orders_items_names( $item_name ) { $item_name = 'mydesiredproductname'; return $item_name; }
But I do not know how to add an incremental number to the product name.
Is there anyone who knows how to do this? Or can point me in the right direction?
Advertisement
Answer
The woocommerce_order_item_name
filter hook is called multiple times,
therefore it is difficult to add a number in the function itself.
Via woocommerce_checkout_create_order
we first add the number as meta_data
for each $item
. Afterwards via get_meta
, we add the number in front of the product name.
So you get:
function action_woocommerce_checkout_create_order( $order, $data ) { // Start number $number = 1; // Loop through order items foreach ( $order->get_items() as $item_key => $item ) { // Update meta data for each item $item->update_meta_data( '_product_number', $number ); // Number +1 $number = $number + 1; } } add_action( 'woocommerce_checkout_create_order', 'action_woocommerce_checkout_create_order', 10, 2 ); function filter_woocommerce_order_item_name( $item_name, $item ) { // Get meta $product_number = $item->get_meta( '_product_number' ); // NOT empty if ( ! empty ( $product_number ) ) { $item_name = $product_number . '. ' . $item_name; } return $item_name; } add_filter( 'woocommerce_order_item_name', 'filter_woocommerce_order_item_name', 10, 2 );
Note: add is_wc_endpoint_url
, to apply it only for email notifications.
function filter_woocommerce_order_item_name( $item_name, $item ) { // Only for email notifications if ( is_wc_endpoint_url() ) return $item_name; // Get meta $product_number = $item->get_meta( '_product_number' ); // NOT empty if ( ! empty ( $product_number ) ) { $item_name = $product_number . '. ' . $item_name; } return $item_name; } add_filter( 'woocommerce_order_item_name', 'filter_woocommerce_order_item_name', 10, 2 );