It's not possible to remove it with remove_action()
the way you've written it.
When you hooked it here:
add_action( 'woocommerce_shop_loop_item_title', array( $this, 'change_title' ), 10 );
The $this
means that the function that's hooked is on this specific instance of My_class
. When using remove_action()
you need to pass the same instance of the class:
remove_action( 'woocommerce_before_shop_loop_item_title', array( $instance, 'change_title' ), 10 );
(where $instance
is the instance of the class).
The problem is that the instance of the class is not available anywhere else because you've instantiated into nothing:
return new My_class();
To remove the action you need to put the class instance into a variable and then use that variable to remove it later:
$my_class = new My_class();
Then in your other code:
global $my_class;
remove_action( 'woocommerce_before_shop_loop_item_title', array( $my_class, 'change_title' ), 10 );
Another option is that if change_title
is static then you don't need a specific instance of the class to add and remove it from hooks.
So make the function static:
public static function change_title() {
echo 'The title';
}
Then to hook a static method you do this:
add_action( 'woocommerce_shop_loop_item_title', array( 'My_class', 'change_title' ), 10 );
Which means you can remove it like this:
remove_action( 'woocommerce_before_shop_loop_item_title', array( 'My_class', 'change_title' ), 10 );
But whether your class/functions can or should be static is a larger architectural question that would depend on exactly what you're doing.