duanhuhong5255 2017-02-15 08:02 采纳率: 0%
浏览 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 请问一下这个运行结果是怎么来的
  • ¥15 这个复选框什么作用?
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下