最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - I want to show cart items number if any or nothing, simple CART text

programmeradmin1浏览0评论

I am making a custom WooCommerce site and stuck at coding the CART link.

I want the link to look simple text "CART" when there is no item in it. But to show the number of items if any like "CART (1)"--- is it possible ?

I am currently using this code which I feel shows "0" of no item.

<a href="<?php echo esc_url(get_page_link(12)); ?>">Cart (<?php echo WC()->cart->get_cart_contents_count(); ?>)</a>

Can someone please help me out with this??? I want a conditional php code to show Cart items number only if there are any, otherwise show nothing.

I am making a custom WooCommerce site and stuck at coding the CART link.

I want the link to look simple text "CART" when there is no item in it. But to show the number of items if any like "CART (1)"--- is it possible ?

I am currently using this code which I feel shows "0" of no item.

<a href="<?php echo esc_url(get_page_link(12)); ?>">Cart (<?php echo WC()->cart->get_cart_contents_count(); ?>)</a>

Can someone please help me out with this??? I want a conditional php code to show Cart items number only if there are any, otherwise show nothing.

Share Improve this question asked Nov 20, 2020 at 7:44 Rishabh JhaRishabh Jha 1
Add a comment  | 

1 Answer 1

Reset to default 0

You're already on the right track. Simply add conditional if 0

<?PHP

$cart_count = WC()->cart->get_cart_contents_count();
$cart_count = $cart_count ? "({$cart_count})" : ''; // if 0, become empty string
$cart_link = wc_get_cart_url();

$cart_button = "<a href='{$cart_link}'>Cart {$cart_count}</a>";

echo $cart_button;
发布评论

评论列表(0)

  1. 暂无评论