Antonin_artaud Antonin_artaud - 3 months ago 17
PHP Question

Redirecting conflicts with WooCommerce cart count condition

I'm using Woocommerce
I have setup some code to redirect to the shop page if I want to access the checkout when my cart is empty. Here is the code

add_action('template_redirect', 'go_away');
function go_away() {
if (is_user_logged_in() && is_checkout() && WC()->cart->cart_contents_count == 0){
wp_redirect(get_permalink(get_option('woocommerce_shop_page_id')));
exit;
}
}


This works fine. However, when I pay for something, I cannot access the "thankyou" page. The cart is considered empty and my code redirects me straightaway to the shop page !

Is there another way I could access the "thankyou" page after checking out, or another way to restrict access to checkout if the cart is empty ?

Answer

Try this

add_action('template_redirect', 'go_away');
function go_away() {
    if (is_user_logged_in() && is_checkout() && WC()->cart->cart_contents_count == 0){
        if ( $_GET["key"] != "") {
            wp_redirect(get_permalink(get_option('woocommerce_shop_page_id')));
            exit;
        }
    }
}
Comments