问题
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 );
}
回答1:
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 function.php file of your active child theme (or active theme). It should work.
回答2:
This works fine, as i said in the comment your code doesn't work i don't know why i just edited it like that it worked but i don't know if it now works fine as the condition to work only executed if cart is not empty on all other pages than cart and checkout)
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 );
}
}
I think there is an issue with this ! ( WC()->cart->is_empty() )
I think this function maybe doesn't work with the operator "!", my code executes the same as yours but i don't know why yours no
来源:https://stackoverflow.com/questions/55254862/clear-woocommerce-cart-on-page-load-even-for-logged-in-users