The goal is to change the name of the item as it gets passed to our payment gateway, but leave it as-is for display on our product pages.
I've tried this in my functions.php:
function change_item_name( $item_name, $item ) {
$item_name = 'mydesiredproductname';
return $item_name;
}
add_filter( 'woocommerce_order_item_name', 'change_item_name', 10, 1 );
But it doesn't seem to be working for me. I feel like I should be passing in an actual item ID or something… I'm a little lost.
Any information on what I'm doing wrong here would be greatly appreciated.
The woocommerce_order_item_name
filter hook is a front-end hook and is located in:
1) WooCommerce templates:
2)WooCommerce Core file:
Each of them has $item_name common first argument, and different for the other arguments.
See Here for more details…
You have 2 arguments set in your function (the second one is not correct for all templates) and you are declaring only one in your hook. I have tested the code below:
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;
}
And it works on
But NOT in Cart, Checkout and Backend Order edit pages.
So if you need to make it work on Cart and Checkout, you should use other hooks like
woocommerce_before_calculate_totals
.
Then you can useWC_Product methods
(setter and getters).
Here is your new code
add_action( 'woocommerce_before_calculate_totals', 'custom_cart_items_prices', 10, 1 );
function custom_cart_items_prices( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item ) {
// Get an instance of the WC_Product object
$product = $cart_item['data'];
// Get the product name (Added Woocommerce 3+ compatibility)
$original_name = method_exists( $product, 'get_name' ) ? $product->get_name() : $product->post->post_title;
// SET THE NEW NAME
$new_name = 'mydesiredproductname';
// Set the new name (WooCommerce versions 2.5.x to 3+)
if( method_exists( $product, 'set_name' ) )
$product->set_name( $new_name );
else
$product->post->post_title = $new_name;
}
}
Code goes in any php file of your active child theme (or theme) or also in any plugin php file.
Now you have change the names everywhere except on Shop archives and product pages…
This code is tested and works on WooCommerce 2.5+ and 3+
If you want to keep original item names in cart only you should add this conditional WooCommerce tag inside the function:
if( ! is_cart() ){ // The code }
This answer has been updated on August 1st 2017 to get a woocommerce compatibility prior versions…
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With