Search code examples
phpwordpresshttp-redirectwoocommercecart

Disable cart page but keep the checkout page in Woocommerce


I'm currently looking for a better way then this question here to remove / disable the cart page in my WooCommerce installation:

Disabling shopping basket in WooCommerce

So I want to show a 404 instead of a redirect so that it's clear that this page doesn't exists.

The functionality must be there because my shop can't work anymore without this.

To make all clear:


I've build a custom button which adds the products to the "cart" and redirect directly to the checkout page. This should be the only available process!


Solution

  • Try the following that will handle cart redirection:

    add_action( 'template_redirect', 'skip_cart_redirect' );
    function skip_cart_redirect(){
        // Redirect to checkout (when cart is not empty)
        if ( ! WC()->cart->is_empty() && is_cart() ) {
            wp_safe_redirect( wc_get_checkout_url() ); 
            exit();
        }
        // Redirect to shop if cart is empty
        elseif ( WC()->cart->is_empty() && is_cart() ) {
            wp_safe_redirect( wc_get_page_permalink( 'shop' ) );
            exit();
        }
    }
    

    Code goes in function.php file of your active child theme (or active theme). It should works.


    If you want to have a 404 for cart page you can use a fake page url that will make a 404 like:

    add_action( 'template_redirect', 'cart_redirect_404' );
    function cart_redirect_404(){
        // Redirect to non existing page that will make a 404
        if ( is_cart() ) {
            wp_safe_redirect( home_url('/cart-page/') ); 
            exit();
        }
    }
    

    Code goes in function.php file of your active child theme (or active theme). It should works.