Filter woocommerce_order_item_name breaking on $prod->get_title() ?

Recently I have had 2 people come up with the same question / problem. I was able to give them really basically the same answer. Looking through their logs I found that the problem both times had to do with getting the title of the product, $_product->get_title() within the woocommerce_order_item_name filter.

What their goals were was to add extra information when displaying a products name, such as the categories or the tags. Both were hooking into the same filter, both were running similar logic. Almost like they both grabbed the same snippet from some a stack overflow post.

Looking at both error logs, both pointed to a line that was calling $_product->get_title(), seems legit. So why isn’t it working? Well, not too sure – haven’t run into that issue because there was no need to even call it.

Here is the code that was broken for both users:

function test_function( $name, $item){
	$product_id = $item['product_id'];
	$_product = wc_get_product( $product_id );
	$htmlStr = $_product->get_title();
	return $htmlStr;
add_filter('woocommerce_order_item_name', 'test_function', 10, 2);

The code above is being called whenever the woocommerce_order_item_name filter is applied, for example – a customer’s Order Details page under their account. There are many things that you could want a customer to see, like categories or tags.

So how do we fix the $_product->get_title() problem?

Simple answer, we don’t. We use what was already handed to us! We already were handed the product name (title) AND the product object as well, so no need to call wc_get_product(), right? This would just slow us down or allow room for error.

The arguments for the woocommerce_order_item_name filter:

  • $name = Link to product page with product name as the display
  • $item = Product object

Knowing this, there is no reason to include line #3 in the above snippet, seeing as $name has the title and you can also get it from $item->get_name().

Going this route, you get the same results without the risk of error!
Here is a working version:

function test_function( $name, $item){
	return strip_tags($name); // Remove strip_tags() to allow product to be a link;
add_filter('woocommerce_order_item_name', 'test_function', 10, 2);

Wow, that is much cleaner!

Hope this helps those out there banging their head on the desk wondering whyyyyy! Feel free to share, I would appreciate it.

By | 2017-05-31T11:40:30-07:00 May 31st, 2017|Categories: Tips & Tricks|Tags: , , , |0 Comments

About the Author:

Originally born in Florida, moved to Arizona and started programming at 13, now 29. Enjoying life with computers, sports, skateboarding and my family. I enjoy short walks on the beach (I get tired fast), loud music (hit me with that bass) and to help others succeed.

Leave A Comment