Hi I am working on a WOOCOMMERCE site and I am trying to redirect user to a custom page when the user tries to add his first product into the cart.
The redirection should be done only for the first product in the cart.
When the user adds two or more products in the cart then the normal ajax add to cart should function.
Firstly I tried redirecting to custom page for the first product by using the function below
function my_custom_add_to_cart_redirect( $url ) {
if (WC()->cart->get_cart_contents_count() == 0)
$url = get_permalink( 1172 ); /* ID of the page is entered */
return $url;
}
add_filter( 'woocommerce_add_to_cart_redirect', 'my_custom_add_to_cart_redirect' );
The above code does redirect to custom page but it happens for all product additions to cart.
Moreover it does not work when "Redirect to the cart page after successful addition" field is unchecked in WOOCommerce Settings.
Can anyone help me with the right approach ?
You need some additional code to disable add to cart when cart is empty and to change a bit your code:
// Replacing the ajax add to cart button by a link to the product when cart is empty
add_filter( 'woocommerce_loop_add_to_cart_link', 'replace_loop_add_to_cart_button', 10, 2 );
function replace_loop_add_to_cart_button( $button, $product ) {
if( WC()->cart->is_empty() && $product->is_type('simple') ){
$button_text = __( "View product", "woocommerce" );
$button = '<a class="button product_type_simple" href="' . $product->get_permalink() . '">' . $button_text . '</a>';
}
return $button;
}
// Custom Redirect on first added to cart only
add_filter( 'woocommerce_add_to_cart_redirect', 'custom_add_to_cart_redirect_on_first_item' );
function custom_add_to_cart_redirect_on_first_item( $url ) {
// Redirect on first added item
if ( WC()->cart->get_cart_contents_count() == 1 ) {
return get_permalink( 1172 ); // ID of the page
}
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.