'Custom add to cart button URL for specific product in WooCommerce?

I would like the user to be directed to a certain URL when they click the 'add to cart' button. At the moment I have this:

/**
 * Set a custom add to cart URL to redirect to
 * @return string
 */
  function custom_add_to_cart_redirect() { 
return 'http://www.yourdomain.com/your-page/'; 
}
add_filter( 'woocommerce_add_to_cart_redirect', 
'custom_add_to_cart_redirect' );

However, this redirects all add to cart buttons, how can I make the URL specific to the product? Thanks



Solution 1:[1]

add_filter( 'woocommerce_add_to_cart_redirect', 'productbase_redirect_on_add_to_cart' );
function productbase_redirect_on_add_to_cart() {

    //Get product ID
    if ( isset( $_POST['add-to-cart'] ) ) {
        $product_id = (int) $_POST['add-to-cart'] ;             
    }
    // set redirect with product id here

}

Solution 2:[2]

You need to use some conditional logic to alter the returned url when those certain conditions are met. The following will alter the url when the product that is added to the cart has the ID of 999.

add_filter( 'woocommerce_add_to_cart_redirect', 'custom_add_to_cart_redirect' );

function custom_add_to_cart_redirect( $url ) {

    // The product ID you want a specific redirect for
    $matched_id = 999; 

    // If product ID matches, modify redirect
    if ( isset( $_POST['add-to-cart'] ) ) && $matched_id = (int) $_POST['add-to-cart'] ) {            
      $url = 'http://www.yourdomain.com/your-page/'; 
    }
    // always return a value
    return $url;

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mujuonly
Solution 2 helgatheviking