Empty the cart by the user ID in WooCommerce

/**
 * Empties the cart by the user ID.
 *
 * @see https://wpcodebook.com/empty-cart-user-id-woocommerce/
 * @see https://github.com/woocommerce/woocommerce/blob/9.2.3/plugins/woocommerce/includes/class-wc-cart-session.php#L371
 * @see https://github.com/woocommerce/woocommerce/blob/9.2.3/plugins/woocommerce/includes/class-wc-session-handler.php#L498
 */
function wpcodebook_wc_empty_cart( $user_id ) {

	// Delete the persistent cart permanently.
	delete_user_meta( $user_id, '_woocommerce_persistent_cart_' . get_current_blog_id() );

	// Delete the session from the cache and database.
	$session_handler = new WC_Session_Handler();
	$session_handler->delete_session( $user_id );

}

Leave a Comment