How to change the "add to cart button" text and behavior from woocommerce so that it redirect to a specific url?

How to change the "add to cart button" text and behavior from woocommerce so that it redirect to a specific url?
typescript
Ethan Jackson

I use woocommerce and I need, for a certain category of product (category = "flash"), that the "add to cart" button from the single product page displays "schedule" and redirect the user to a form without adding the product to the cart.This is a schedule form with a checkout at the end of it. I wan't all the product info to be transfered as we go through the form (I want to autofill some parts of the form with the name of the product and its price for example)

My guess was to delete the button from the single product page and then add a new button that juste redirect to my form. For now, I can't even remove the native woocommerce button, I tried this code (that I found here on StackOverflow) that is supposed to remove the button if the product is from the "flash" category :

add_action('woocommerce_single_product_summary', 'wc_flash_button_replacement'); function wc_flash_button_replacement() { if (has_term('flash', 'product_cat')) { remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30); } }

But with this code, the button is still on my single product page (I use Code Snippets)

Answer

To change the "Add to Cart" button text and make it redirect to a specific URL in WooCommerce, you can use a custom code snippet in your theme’s functions.php file or a code snippets plugin. Here's how:

php

CopyEdit

add_filter( 'woocommerce_loop_add_to_cart_link', 'custom_add_to_cart_redirect_button', 10, 2 ); function custom_add_to_cart_redirect_button( $button, $product ) { $custom_url = 'https://example.com/custom-page'; // Replace with your target URL $button_text = 'Buy Now'; // Custom button text if ( $product->is_type( 'simple' ) ) { $button = '<a href="' . esc_url( $custom_url ) . '" class="button add_to_cart_button">' . esc_html( $button_text ) . '</a>'; } return $button; }

This snippet changes the button text and redirects users to your custom URL instead of adding the product to the cart. For more advanced control, you can modify the logic to target specific products, categories, or product types.

Related Articles