WooCommerce add to cart redirect hook with a query parameter passed

Viewed 583

I am trying to use woocommerce_add_to_cart_redirect to redirect the user to the product page, and add a custom query data.

function my_custom_add_to_cart_redirect( $url ) {
  $currentProductUrl = "";
  $redirectUrl = esc_url( add_query_arg('cart', true, $currentProductUrl ));
  return $redirectUrl;
}

add_filter( 'woocommerce_add_to_cart_redirect', __NAMESPACE__ .'\\my_custom_add_to_cart_redirect' );

How do I get $currentProductUrl ??

1 Answers

In woocommerce_add_to_cart_redirect hook, there is an additional argument only on normal add to cart (not with Ajax add to cart) that is the WC_Product Object instance.

This way you can get the product permalink and add to it your query arguments only on single add to cart.

add_filter( 'woocommerce_add_to_cart_redirect', 'my_custom_add_to_cart_redirect', 10, 2 );
function my_custom_add_to_cart_redirect( $url, $product ) {
    if ( $product && is_a( $product, 'WC_Product' ) ) {
        $url = esc_url( add_query_arg('cart', true, $product->get_permalink() ) );
    }
    return $url;
}

For Ajax add to cart that argument is null (see that in here).

Related