Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

php - Redirect to shop if cart is emptied on cart page in WooCommerce 3+

In WooCommerce I want to redirect from cart to shop page when cart is empty and I am using this code:

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

This code works only if cart is empty and I try to go on cart page. But if I am already on cart page and I remove all cart items, I have to reload the page to get redirected. So I guess I have to add something in the code to reload the page. Any thoughts?

I would appreciate if anyone could help me with this.

question from:https://stackoverflow.com/questions/65853947/redirect-to-shop-if-cart-is-emptied-on-cart-page-in-woocommerce-3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your code is a bit obsolete since WooCommerce version 3. Now on cart page, PHP redirect is useless, because Emptying cart is an Ajax customer live event. So in this case Javascript (jQuery) is required.

Use the following instead, that handle all cases:

add_action( 'template_redirect', 'empty_cart_redirection' );
function empty_cart_redirection(){
    if( is_cart() ) :
    
    // Here set the Url redirection
    $url_redirection = get_permalink( wc_get_page_id( 'shop' ) );
    
    // When trying to access cart page if cart is already empty  
    if( WC()->cart->is_empty() ){
        wp_safe_redirect( $url_redirection );
        exit();
    }
    
    // When emptying cart on cart page
    wc_enqueue_js( "jQuery(function($){
        $(document.body).on( 'wc_cart_emptied', function(){
            if ( $( '.woocommerce-cart-form' ).length === 0 ) {
                $(window.location).attr('href', '" . $url_redirection . "');
                return;
            }
        });
    });" );
    endif;
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works in all WooCommerce versions since version 3.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...