0

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.

1 Answer 1

0

Try with below code. i have tested and it is working fine for me.

add_filter( 'woocommerce_add_to_cart_redirect', 'acf_product_redirect' );
function acf_product_redirect() {
    #Get product ID
    if ( isset( $_REQUEST['add-to-cart'] ) ||  is_numeric( $_REQUEST['add-to-cart'] ) ) {
        $product_id = (int) apply_filters( 'woocommerce_add_to_cart_product_id', $_REQUEST['add-to-cart'] );
        # Check if redirect url set or not
        if (!empty(get_field('redirect_url', $product_id))) {
            $redirect_id = get_field('redirect_url', $product_id); 
            return get_permalink($redirect_id);
        }   
    }
}

Let me know if this works for you.

1
  • That works! So it must be the difference in how we were both getting the product ID. Really appreciate you providing the solution. Commented Oct 14, 2019 at 14:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.