WooCommerce – Overwrite action hook [closed]

Within the WooCommerce template file “content-product.php”, I’m trying to overwrite the following action hook:

/**
* woocommerce_shop_loop_item_title hook
*
* @hooked woocommerce_template_loop_product_title - 10
*/
do_action( 'woocommerce_shop_loop_item_title' );

To overwrite this hook, I have added the following to my functions.php file:

add_action(‘woocommerce_shop_loop_item_title’, ‘change_product_title’);

function change_product_title() {
    echo'<header class="entry-header"><h1 class="entry-title">'.get_the_title().'</h1></header>';
}

This only adds to the hook. How do I completly replace the hook with my own code? I have checked the WooCommerce documentation, but it doesn’t give you a great deal to go on.

2 Answers
2

It’s actually pretty simple to change the title in content-product.php, but you won’t be able to do it with a hook. Near the top of the file, you should see this line:

Override this template by copying it to yourtheme/woocommerce/content-product.php

All you have to do is copy the file to the above directory, replacing “yourtheme” with your theme’s actual folder name, and make your desired edits to the new file.

A little more background on hooks

The title in the default content-product.php template file is outputted like this, which is defined in wc-template-functions.php if you search for woocommerce_template_loop_product_title() it echos the below title:

<h3><?php the_title(); ?></h3>

In order to change the title with a hook, you’d need to change the above line to this, but you can’t do this without changing the wc-template-functions.php file. So what you can do is comment out the action in the content-product.php file:

//do_action( 'woocommerce_shop_loop_item_title' );

and then add the below line:

?><h3><?php echo apply_filters( 'my_filter_name', get_the_title() ); ?></h3><?php

so the saved version looks like this:

//do_action( 'woocommerce_shop_loop_item_title' );
?><h3><?php echo apply_filters( 'my_filter_name', get_the_title() ); ?></h3><?php

Then, you would need to add the following to your theme’s functions.php file which will pass the contents of get_the_title() to the $title parameter, which you can then change any way you wish, but in the below case will change every title to say “Custom Title”:

add_filter( 'my_filter_name', 'my_custom_function' );

function my_custom_function( $title ) {
  return 'Custom Title';
}

For more information, see the following:

http://codex.wordpress.org/Function_Reference/apply_filters

http://codex.wordpress.org/Function_Reference/add_filter

Leave a Comment