Removing a Wordpress action added from a Plugin and than adding a new action in place of that

412 views Asked by At

I am creating a wordpress theme and i need to remove a wordpress action added from within a plugin class.

Here is the plugin's class and the action added in this class is add_action( 'woocommerce_after_shop_loop_item', array( $this, 'add_compare_link' ), 20 ); And this is the action i need to remove in my theme.

After removing that action i need to add a new action on the same location. New action is:

function product_add_compare_link( $product_id = false, $args = array() ) {
    extract( $args );
    if ( ! $product_id ) {
        global $product;
        $product_id = isset( $product->id ) && $product->exists() ? $product->id : 0;
    }
    if ( empty( $product_id ) ) return;
    $is_button = !isset( $button_or_link ) || !$button_or_link ? get_option( 'yith_woocompare_is_button' ) : $button_or_link;
    $button_text = get_option( 'yith_woocompare_button_text', __( 'Compare', 'yit' ) );
    $localized_button_text = function_exists( 'icl_translate' ) ? icl_translate( 'Plugins', 'plugin_yit_compare_button_text', $button_text ) : $button_text;
    printf( '<a href="%s" class="%s" data-product_id="%d"><i class="icon-tasks"></i>%s</a>', $this->add_product_url( $product_id ), 'compare' . ( $is_button == 'button' ? ' add-comp' : '' ), $product_id, ( isset( $button_text ) &&      $button_text != 'default' ? $button_text : $localized_button_text ) );
}
add_action( 'woocommerce_after_shop_loop_item', 'product_add_compare_link', 20 );

Tried this solution and it removed that action perfectly but i cannot add a new one after that.

What i am doing is:

function kill_old_action() {
    remove_anonymous_object_filter(
        'woocommerce_after_shop_loop_item',
        'YITH_Woocompare_Frontend',
        'add_compare_link'
    );
}
add_action( 'woocommerce_after_shop_loop_item', 'kill_old_action', 0 ); 
add_action( 'woocommerce_after_shop_loop_item', 'product_add_compare_link', 50 );

Any help will be highly appreciated.

Thank you

1

There are 1 answers

0
James Jones On

I wouldn't remove the action like that. The traditional way to remove an action that was added from a class is:

remove_action('woocommerce_after_shop_loop_item', array( $class_variable, 'add_compare_link' ), 20  );

where the class variable is the instantiation of the class. How you refer to this depends on how the class has been instantiated in the plugin.

You can read about different ways of instantiating a class and the corresponding remove_action at http://jespervanengelen.com/different-ways-of-instantiating-wordpress-plugins/

Also when you use add_action if you want to be able to use more than one input parameter in your function you need to specify the number of parameters. So in your case:

add_action( 'woocommerce_after_shop_loop_item', 'product_add_compare_link', 50, 2 );