Am I doing something wrong using the below code to have the function of Redirection to an external / third party URL when Add to Cart on WooCommerce site?
add_filter( 'woocommerce_add_to_cart_redirect', 'custom_add_to_cart_redirect', 10, 2 );
function custom_add_to_cart_redirect( $redirect_url) {
$redirect_url = "https://IWANTTOREDIRECTHERE.COM";
return $redirect_url;
}
I would like the redirect to external url for ALL products globally across the site but, not sure how I can go about doing this.
2
Answers
I have resolved this by applying the following steps:
Firstly, for external urls, we must whitelist the domain using the "allowed_redirect_hosts" hook:
Then, we must use the woocommerce_add_to_cart_redirect hook like so:
This works for the Add to Cart button on Category Page and Single Product Page. Tested and works... Hope it helps anyone else looking to do the same!
This script targets the add-to-cart button on a single product page. Adjust the selector if your setup is different. When the button is clicked, it prevents the default action (adding to the cart) and redirects the user to the specified URL.