如何在 wordpress 上用 PHP/Javascript if/else 条件隐藏 类?

How to hide classes with PHP/Javascript if/else conditional at wordpress?

我在 Wordpress 函数的条件 (if/else) 方面遇到了一些问题。 如果购物车上的值 $xs_product_count 为 0,我需要隐藏此 <span class="xs-item-count highlight xscart"><?php echo esc_html($xs_product_count); ?></span>。 我该怎么办?

我试过使用 PHP 本机,但我的网站有错误。

我的物品代码是:

<a href="<?php echo esc_url( wc_get_cart_url() ); ?>" class ="mobile-cart-notif offset-cart-menu">
   <span class="xs-item-count highlight xscart">
      <?php echo esc_html($xs_product_count); ?>
   </span>
   <i class="icon icon-bag"></i>
</a>
<a href="<?php echo esc_url( wc_get_cart_url() ); ?>" class ="mobile-cart-notif offset-cart-menu">
<?php if (0 < $xs_product_count) {?>
   <span class="xs-item-count highlight xscart">
      <?php echo esc_html($xs_product_count); ?>
   </span>
<?php } ?>
   <i class="icon icon-bag"></i>
</a>

您可以在 span 标签前使用以下条件。

<a href="<?php echo esc_url( wc_get_cart_url() ); ?>" class ="mobile-cart-notif offset-cart-menu">
<?php     
if($xs_product_count != 0 ){
?>
   <span class="xs-item-count highlight xscart">
      <?php echo esc_html($xs_product_count); ?>
   </span>
<?php } ?>
   <i class="icon icon-bag"></i>
</a>

或者您可以通过下面的代码隐藏完整的部分。

<?php     
if($xs_product_count != 0 ){
?>
<a href="<?php echo esc_url( wc_get_cart_url() ); ?>" class ="mobile-cart-notif offset-cart-menu">

   <span class="xs-item-count highlight xscart">
      <?php echo esc_html($xs_product_count); ?>
   </span>
   <i class="icon icon-bag"></i>
</a>
<?php } ?>

我会试试这个:

<a href="<?php echo esc_url( wc_get_cart_url() ); ?>" class="mobile-cart-notif offset-cart-menu">
    <?php if ((int) $xs_product_count > 0) : ?>
        <span class="xs-item-count highlight xscart">
            <?php echo esc_html($xs_product_count); ?>
        </span>
    <?php endif; ?>
   <i class="icon icon-bag"></i>
</a>

if语句中把(int)放在$xs_product_count前面就叫做“casting”变量为类型,它会改变'0' 到整数 0 的字符串,这让我们可以可靠地与 > 运算符进行比较。