WooCommerce: Automatic redirect after add-to-cart

By default, WooCommerce displays an alert message after you add a product to the cart.

Sometimes it’s necessary to redirect checkout or any other page.

No Code Solution

Coding Solution

The way is straightforward but requires enabling Redirect to the cart page after successful addition.

enable redirect to the cart page
/**
 * Redirect users after add to cart.
 */
function redirect_after_add_to_cart_single( $url ) {
	return wc_get_checkout_url();
}

add_filter( 
  'woocommerce_add_to_cart_redirect', 
  'redirect_after_add_to_cart_single' 
);
PHP

Here woocommerce_add_to_cart_redirect hook contains 2-parameters,

  1. URL
  2. Product Object or Null

So, You can perform several checks before returning the actual URL.

/**
 * Redirect users after add to cart if product is simple.
 *
 * @param string           $url URL.
 * @param \WC_Product|null $product Product.
 *
 * @return string
 */
function redirect_after_add_to_cart_single( $url, $product ) {
	if ( $product && $product->is_type( 'simple' ) ) {
		return wc_get_checkout_url();
	}

	return $url;
}


add_filter( 
  'woocommerce_add_to_cart_redirect', 
  'redirect_after_add_to_cart_single', 10, 2 
);
PHP

Thanks.

Istiaq Nirab

A highly skilled and proficient WordPress developer with over Three years of professional experience in all aspects of WordPress website creation, including design, plug-ins, and implementation. Results-driven individual contributor with a successful track record in exceeding expectations for web development initiatives

More Reading

Post navigation

Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *