Redirect to home if the cart is empty in Woocommerce

谁说胖子不能爱 提交于 2019-12-11 06:38:09

问题


I am looking for and can not find anywhere as I can redirect the empty woocommerce cart to the homepage. I only find redirects that go to the store.

This is what I find, but I do not need to redirect to the home:

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' ) ) );
    }
}

Context link: if cart is empty, the cart page will redirect to shop page in woocommerce?

Thank you


回答1:


To redirect to home if cart is empty you will use a similar code:

add_action( 'template_redirect', 'empty_cart_redirection' );
function empty_cart_redirection(){
    if( WC()->cart->is_empty() && ! ( is_front_page() || is_cart() ) ){
        wp_safe_redirect( esc_url( home_url( '/' ) ) );
        exit;
    }
}

Code goes in function.php file of your active child theme (active theme). Tested and works.

But if cart is emptied through ajax, this code will enable a redirection to home until the page will be reloaded.



来源:https://stackoverflow.com/questions/53288200/redirect-to-home-if-the-cart-is-empty-in-woocommerce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!