skip to Main Content

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


  1. Chosen as BEST ANSWER

    I have resolved this by applying the following steps:

    Firstly, for external urls, we must whitelist the domain using the "allowed_redirect_hosts" hook:

    add_filter( 'allowed_redirect_hosts', 'mycustom_extend_allowed_domains_list' );
    function mycustom_extend_allowed_domains_list( $hosts ){
        
        $hosts[] = 'wordpress.com';
        $hosts[] = 'externaldomainhere.com';
        
        return $hosts;
        
    }
    

    Then, we must use the woocommerce_add_to_cart_redirect hook like so:

    add_filter( 'woocommerce_add_to_cart_redirect', 'custom_add_to_cart_redirect', 10, 1 );
    function custom_add_to_cart_redirect( $redirect_url) {
        $redirect_url = 'https://externaldomainhere.com';
        wp_safe_redirect( $redirect_url );
        exit;
    }
    

    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!


  2. 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.

    // Wait for the DOM to be ready
    document.addEventListener('DOMContentLoaded', function () {
        // Find the add-to-cart button
        var addToCartButton = document.querySelector('.single_add_to_cart_button');
    
        // Check if the button exists
        if (addToCartButton) {
            // Add a click event listener to the button
            addToCartButton.addEventListener('click', function (event) {
                // Prevent the default action of the button (adding to the cart)
                event.preventDefault();
    
                // Perform your custom redirection
                window.location.href = 'https://example.com'; // Replace with your desired URL
            });
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search