Forum

Thread tagged as: Shop

Testing for items in cart

How would I test for the presence of items in the cart? For example I have this in my product display template:

<li><a class="btn  btn--checkout" href="/cart">View Cart</a></li>

Can I do something like this:

<perch:if exists="test-for-items-in-cart">
    <li><a class="btn  btn--checkout" href="/cart">View Cart</a></li>
</perch:if>
Winston Grace

Winston Grace 0 points

  • 3 years ago
Drew McLellan

Drew McLellan 2638 points
Perch Support

Do you want to test for specific items, or just if there's anything at all in the cart?

Hussein Al Hammad

Hussein Al Hammad 105 points
Registered Developer

Hello Winston,

If you want to check whether there's anything in the cart, you can use perch_shop_cart_item_count() to get the number of items in your cart and if there is any, pass a variable into your template.

In your page.php:

$cart_count = perch_shop_cart_item_count([], true); 
if($cart_count) {
    PerchSystem::set_var('items_in_cart', true);
}

And in your template.html:

<perch:if exists="items_in_cart">
    <li><a class="btn btn--checkout" href="/cart">View Cart</a></li>
</perch:if>

Just if theres anything in the cart. I discovered perch_shop_cart_item_count() but wasn't sure how to use that within template files. Thanks for the help.