Skip to main content
add questions related tags
Link
fuxia
  • 107.1k
  • 38
  • 255
  • 459
Source Link

WooCommerce and ACF: How to Redirect Upon Add to Cart - Partially Working Example

I'm using ACF on product pages to select a desired redirect URL after the product is added to the cart. Main use for this is to redirect to custom up sell pages.

Example: Product A has the ACF field "Redirect URL" populated with Product B. When Product A is added to cart, the user is redirected to Product B.

I have the following code in my functions.php:

function acf_product_redirect( $url ) {
    global $post; 
    
    if (get_field('redirect_url', $post->ID)) {
        $redirect_id = get_field('redirect_url', $post->ID); 
        $url = get_permalink($redirect_id);
        var_dump($url); // This $url var correctly displays my desired redirect URL
        return $url;    
    }


}

add_filter( 'woocommerce_add_to_cart_redirect', 'acf_product_redirect' );

While viewing a single product page, var_dump($url) correctly displays the URL that I set on the product page. But... the redirect doesn't actually work.

If I move the 'return $url' line outside of the if statement and replace the $url variable with a static url, the redirect works.

So something is happening after I click Add to cart. That $url variable is not being passed on.