【问题标题】:How to add an if statement into this php function如何在这个 php 函数中添加 if 语句
【发布时间】:2013-05-11 13:43:03
【问题描述】:

我需要在下面的代码中插入if 语句:

add_filter('add_to_cart_fragments', 'woocommerce_header_add_to_cart_fragment');
function woocommerce_header_add_to_cart_fragment( $fragments ) {
    global $woocommerce;
    ob_start();
?>
    <a class="cart-contents" href="<?php echo $woocommerce->cart->get_cart_url(); ?>" 
       title="<?php _e('View your shopping cart', 'woothemes'); ?>">

        <?php echo sprintf(_n('%d item', '%d items',
                $woocommerce->cart->cart_contents_count, 'woothemes'), 
                $woocommerce->cart->cart_contents_count);?> - 
        <?php echo $woocommerce->cart->get_cart_total(); ?>

    </a>
    <?php
        $fragments['a.cart-contents'] = ob_get_clean();
        return $fragments;
}

这是针对 woocommerce 的。它按内容编号显示购物车。 我需要一个类似这样的if 声明:

if ( sizeof( $woocommerce->cart->cart_contents ) == 0 ) {
echo 'empty cart';
}
else ...

因此,当购物车为空时,它会显示一条消息。我不知道怎么把这个写到那个函数里。

【问题讨论】:

  • Emaxx Zeppie:你能澄清一件事吗??? $woocommerce-&gt;cart-&gt;cart_contents_count 是一个数字(不是数组)对吗???
  • cart_contents_count 返回一个整数
  • 在这种情况下,只需if(($woocommerce-&gt;cart-&gt;cart_contents_count) == 0) 就足够了...不需要sizeof()...

标签: php wordpress numbers cart woocommerce


【解决方案1】:

替换这个

<a class="cart-contents" href="<?php echo $woocommerce->cart->get_cart_url(); ?>" 
   title="<?php _e('View your shopping cart', 'woothemes'); ?>">

    <?php echo sprintf(_n('%d item', '%d items',
            $woocommerce->cart->cart_contents_count, 'woothemes'), 
            $woocommerce->cart->cart_contents_count);?> - 
    <?php echo $woocommerce->cart->get_cart_total(); ?>

</a>


有了这个
<?php if((sizeof($woocommerce->cart->cart_contents)) == 0): 
    echo 'empty cart';
?>
<?php else: ?>
  <a class="cart-contents" href="<?php echo $woocommerce->cart->get_cart_url(); ?>" 
       title="<?php _e('View your shopping cart', 'woothemes'); ?>">

        <?php echo sprintf(_n('%d item', '%d items',
                $woocommerce->cart->cart_contents_count, 'woothemes'), 
                $woocommerce->cart->cart_contents_count);?> - 
        <?php echo $woocommerce->cart->get_cart_total(); ?>

    </a>
<?php endif; ?>

【讨论】:

  • 即使我的购物车中有零件商品,它仍然会显示“else”状态
  • @EmanueleEmaxxZeppieri 我刚刚发表了评论... :) sizeof($var) == count($var) in PHP 所以即使$var(整数)的值是0 或任何值,sizeof($var) '将永远是 1
  • 我明白了!正确的是“cart_contents”,而不是“cart_contents_count”。现在,它确实有效:D 非常感谢!
  • 所以它的sizeof($woocommerce-&gt;cart-&gt;cart_contents)intval($woocommerce-&gt;cart-&gt;cart_contents_count)
  • sizeof($woocommerce->cart->cart_contents) 对我有用
猜你喜欢
  • 2012-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-13
相关资源
最近更新 更多