Home > Software engineering >  Declaring remove_action inside a class the same way as add_action
Declaring remove_action inside a class the same way as add_action

Time:09-20

When declaring an action in a class, we use this:

class the_class{
    function __construct(){
        add_action( 'the_action', array( $this, 'cb_function' ) ); 
    }
    function cb_function(){
        
    }   
}

We are trying to declare a remove action in a class, we are trying this:

class the_class{
    function __construct(){
        remove_action( 'woocommerce_after_shop_loop_item', array( $this, 'woocommerce_template_loop_add_to_cart' ) ); 
        remove_action( 'woocommerce_single_product_summary', array( $this, 'woocommerce_template_single_add_to_cart' ), 30 ); 
    }
}

But it is not working, what is wrong?

CodePudding user response:

The best practice to write something to remove action, when you're working with a class, should be like this:

Note: when you use remove_action you need to define the priority value as well and some themes can also remove the action and re-apply with different priority so you need to make sure if the theme is changing something, if it is then you need to change your code according to that so that your changes affects the theme changes

class the_class {

    public function __construct() {
        add_action( 'init', array( $this, 'cb_remove_function' ) );
    }

    public function cb_remove_function() {
        remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
        remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
    }
}
  • Related