duanhuhong5255 2017-02-15 08:02
浏览 38
已采纳

PHP foreach代码没有产生预期的结果

The following code is from a wordpress + woocommerce installation. It's supposed to check every item in the cart and if the item belongs to specific product categories (category ids 79 & 130 add 15€ charge, category 80, 136, 139 add 50€ charge) add extra charges accordingly to category. For simplicity I'll call them category group 15€ and category group 50€.

When one item is added to the cart, belonging to either category group 15€ or category group 50€, the additional charge is added as expected.

When two items are added to the cart, belonging to different category groups, the additional charges are added as expected.

But if more than one items are added to the cart, belonging to the same category group, only one charge per category group is added, which is not desirable. Every item added should incur the relevant category group charge. E.g. 2 items of category group 15€ should add 2 additional charges, 3 items of category group 50€ should add 3 additional charges and so on.

Is there a bug in the code or... ?

function woo_add_cart_fee() {

global $woocommerce;

    foreach ($woocommerce->cart->cart_contents as $key => $values ) {
        // Get the terms, i.e. category list using the ID of the product
    $terms = get_the_terms( $values['product_id'], 'product_cat' );
        // Because a product can have multiple categories, we need to iterate through the list of the products category for a match
        foreach ($terms as $term) {
            // 79 is the ID of the category for which we want to remove the payment gateway
            if($term->term_id == '79' || $term->term_id == '130'){
             $excost = 15;
             $woocommerce->cart->add_fee('Εκτύπωση με απλό μελάνι', $excost, $taxable = false, $tax_class = '');
             } else if ($term->term_id == '80' || $term->term_id == '139' || $term->term_id == '136'){
                 $excost = 50;
                 $woocommerce->cart->add_fee('Μακέτα & εκτύπωση (απλό μελάνι)', $excost, $taxable = false, $tax_class = '');
             }
         }
    }
}
  • 写回答

1条回答 默认 最新

  • duanquan1876 2017-02-15 08:19
    关注

    You need to make each fee name unique.

    From the documentation:

    $name - ( string ) required – Unique name for the fee. Multiple fees of the same name cannot be added.

    This would be one way to do it:

    $woocommerce->cart->add_fee('Μακέτα & εκτύπωση (απλό μελάνι) ' . $i++, $excost, $taxable = false, $tax_class = '');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒