I want to clear the cart page on page load if this page is not a cart or a checkout page Even for logged in users and admins, any page then it clears. This code was working but its not anymore
/**
* Clears WC Cart on Page Load
* (Only when not on cart/checkout page)
*/
add_action( 'wp_head', 'bryce_clear_cart' );
function bryce_clear_cart() {
if ( wc_get_page_id( 'cart' ) == get_the_ID() || wc_get_page_id( 'checkout' ) == get_the_ID() ) {
return;
}
WC()->cart->empty_cart( true );
}
Updated and enhanced.
Use WooCommerce conditional tags and try template_redirect
hook instead (when cart is not empty):
add_action( 'template_redirect', 'custom_empty_cart' );
function custom_empty_cart() {
if ( ! ( is_cart() || is_checkout() ) && ! WC()->cart->is_empty() ) {
WC()->cart->empty_cart( true );
}
}
Code goes on the functions.php file of your active child theme* (or in a plugin). It should work.
*Avoid the parent theme because all your customizations will be removed when the theme will be updated.