Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove_action() not working in WordPress plugin

Tags:

wordpress

I'm new to writing WordPress plugins. I'm trying to write a little plugin that modifies how the woocommerce plugin displays images on the single product page. Specifically, if there is no product image, make the div holding the image "display:none" rather than displaying a placeholder image there. The strategy I'm using is to use add_action to render my own version of woocommerce's product_image.php template and then (trying to) use remove_action to prevent the original product_image.php file from being rendered. The add_action is clearly working, as I can see the "display:none" div in Firebug. However, the remove_action isn't succeeding.

Here is my code:

$add_result = add_action( 'woocommerce_before_single_product_summary', 'eba_wc_show_product_images', 10);

function eba_wc_show_product_images() {
    include( 'eba_product-image.php' );
}

$remove_result = remove_action( 'woocommerce_before_single_product_summary', 'woocommerce_show_product_images', 30);
echo "<hr/>result of add_result = " . $add_result . "<hr/>";
echo "<hr/>result of remove_result = " . $remove_result . "<hr/>";

The priority on the original add_action for the woocommerce_before_single_product_summary hook was 20, so I made the priority on the remove_action 30.

The two debugging statements at the end show that the add_action is returning "1", but the result of the remove_action is empty. Any help would be greatly appreciated.

like image 364
Erica Ackerman Avatar asked May 20 '12 13:05

Erica Ackerman


2 Answers

I've stumbled on this question several times now and I wish somebody would've just told me that I can do this:

$priority = has_action('action_name', 'function_name');
remove_action('action_name', 'function_name', $priority);

This saves me from actually hardcoding the priority, which may be different for different environments.

like image 178
peter Avatar answered Oct 20 '22 18:10

peter


Try removing the action during plugins_loaded, this should ensure that its definitely been added before you try and remove it.

add_action('plugins_loaded','alter_woo_hooks');

function alter_woo_hooks() {
    $add_result = add_action( 'woocommerce_before_single_product_summary', 'eba_wc_show_product_images', 10);
    $remove_result = remove_action( 'woocommerce_before_single_product_summary', 'woocommerce_show_product_images', 10);

    echo "<hr/>result of add_result = " . $add_result . "<hr/>";
    echo "<hr/>result of remove_result = " . $remove_result . "<hr/>";
}

function eba_wc_show_product_images() {
    include( 'eba_product-image.php' );
}
like image 37
Rob Holmes Avatar answered Oct 20 '22 16:10

Rob Holmes