Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If cart is empty, the cart page will redirect to shop page in WooCommerce?

In WooCommerce, I want to redirect the cart page to shop page when the cart page is empty otherwise shows the cart page. Can anyone have the solution ?

Here is the code I have tried, but it does not work:

function my_empty_cart() {
  global $woocommerce;

    if (isset( $_GET['empty-cart'] ) ) { 
        wp_safe_redirect( get_permalink( woocommerce_get_page_id( 'product' ) ) );
    }
}
add_action( 'init', 'my_empty_cart' );
like image 748
Lipsa Avatar asked Jun 19 '14 06:06

Lipsa


2 Answers

// old woocommerce : use sizeof( $woocommerce->cart->cart_contents) to check cart content count

// In new woocommerce 2.1+ : WC()->cart->cart_contents_count to check cart content count

add_action("template_redirect", 'redirection_function');
function redirection_function(){
    global $woocommerce;
    if( is_cart() && WC()->cart->cart_contents_count == 0){
        wp_safe_redirect( get_permalink( woocommerce_get_page_id( 'shop' ) ) );
    }
}

init hook will run everytime. use template_redirect

==============Updates=============

In new woocommerce, they have updated the functionality and now you can use following function to directly get the cart content count.

WC()->cart->cart_contents_count

like image 100
Pushpak Patel Avatar answered Sep 26 '22 22:09

Pushpak Patel


Just tested this myself as I needed something similar.

function cart_empty_redirect_to_shop() {
    global $woocommerce;

    if ( is_page('cart') and !sizeof($woocommerce->cart->cart_contents) ) {
        wp_redirect( get_permalink( wc_get_page_id( 'shop' ) ) ); exit;
    }
}

add_action( 'wp_head', 'cart_empty_redirect_to_shop' );
like image 25
adamj Avatar answered Sep 22 '22 22:09

adamj