20th Mar '23
/
2 comments

Is WooCommerce Cart Empty Condition in Bricks

Updated on 5 Nov 2024

Looking to conditionally render an element depending on whether the user’s cart is empty or not when using WooCommerce?

Add the following in child theme‘s functions.php (w/o the opening PHP tag) or a code snippets plugin:

// Function to check if WooCommerce cart is empty.
function bl_is_cart_empty() {
	if ( function_exists( 'WC' ) ) {
		return WC()->cart->is_empty();
	}

	return true;
}

Then whitelist it:

add_filter( 'bricks/code/echo_function_names', function() {
    return [
        'bl_is_cart_empty',
    ];
} );

and use it with a Dynamic data condition of Bricks like this:

{echo:bl_is_cart_empty}

The above will output the element on which that condition has been applied if the cart is empty.

To output the element if the cart is NOT empty, set the value to check against to 0.

Remember that 1 is true and 0 is false.

Note

This result of the condition (or rather, the custom function that it uses) won’t reflect on the front end immediately after all the products have been removed from the cart due to AJAX. But it will work after the user navigates to another page or reloads the page.

Get access to all 632 Bricks code tutorials with BricksLabs Pro

2 comments

Leave a Reply to Michał Czajka (Cancel Reply)

 

Related Tutorials..

Pro
Conditionally Rendering an Element Outside the Loop based on Taxonomy Term in Bricks

Conditionally Rendering an Element Outside the Loop based on Taxonomy Term in Bricks

A user asks: Hiding element based on taxonomy I have an element in a footer that I want to hide if a page has a…
Categories:
Pro
[WooCommerce] Sale price dates in Bricks

[WooCommerce] Sale price dates in Bricks

Outputting start and end sale price dates (if set) for WooCommerce products.
Categories:
Checking if the current post has been published within the last x days

Checking if the current post has been published within the last x days

Conditionally output an element if the current post has been published in the last x number of days.
Categories:
Conditional Output based on Manual Excerpt in Bricks

Conditional Output based on Manual Excerpt in Bricks

How to display a post’s excerpt only if it has been manually set.
Categories:
How To Remove the Featured Image from WooCommerce Product Gallery

How To Remove the Featured Image from WooCommerce Product Gallery

Product Gallery on single product pages in WordPress include the product's featured image by default. If you are looking to exclude it so only the…
Categories:
Pro
Conditionally Outputting Query Loop Item Based on Post Meta in Bricks

Conditionally Outputting Query Loop Item Based on Post Meta in Bricks

Rendering query-loop enabled posts depending on the value of each post's custom field value is tricky because by default, the custom field plugins' functions or…
Categories: