What I am trying to do is
- Input an custom URL from user, save it as product meta.
- If there is an URL set, not empty, then remove add_to_cart button and place in button with custom link.
- If not, add an fall-back to show add to cart button and variations same as it used to be.
Now here is how code looks –
add_action( 'init', array($this, 'woocommerce_custom_add_to_cart_remove_add_to_cart')); // Goes in class constructor.
function woocommerce_custom_add_to_cart_remove_add_to_cart() {
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
remove_action( 'woocommerce_simple_add_to_cart', 'woocommerce_simple_add_to_cart', 30 );
remove_action( 'woocommerce_grouped_add_to_cart', 'woocommerce_grouped_add_to_cart', 30 );
remove_action( 'woocommerce_variable_add_to_cart', 'woocommerce_variable_add_to_cart', 30 );
remove_action( 'woocommerce_external_add_to_cart', 'woocommerce_external_add_to_cart', 30 );
add_action( 'woocommerce_single_product_summary', array($this, 'woocommerce_custom_add_to_cart_custom_button'), 30 );
add_action( 'woocommerce_simple_add_to_cart', array($this, 'woocommerce_custom_add_to_cart_custom_button'), 30 );
add_action( 'woocommerce_grouped_add_to_cart', array($this, 'woocommerce_custom_add_to_cart_custom_button'), 30 );
add_action( 'woocommerce_variable_add_to_cart', array($this, 'woocommerce_custom_add_to_cart_custom_button'), 30 );
add_action( 'woocommerce_external_add_to_cart', array($this, 'woocommerce_custom_add_to_cart_custom_button'), 30 );
}
function woocommerce_custom_add_to_cart_custom_button() {
global $post,$product;
if($this->woocommerce_custom_add_to_cart_get_cartURL() !='')
echo '<form name="custom_cart_button" method="post" action="'.$this->woocommerce_custom_add_to_cart_get_cartURL().'"><button type="submit" class="single_add_to_cart_button button alt">'.$this->woocommerce_custom_add_to_cart_get_carttext().'</button></form><br />';
else {
// What logic should go here to handle the fall back, and show the default add to cart button. adding the actions wont work.
}
}
Try moving the remove_action and add_action code to another hook where you will get the Product ID such as “woocommerce_before_single_product_summary” and check your condition inside it, if it matches then remove default woocommerce hooks and add your hooks.
And do not remove the hook “woocommerce_single_product_summary -> woocommerce_template_single_add_to_cart” and add it back since it is not needed.