duanfuxing2212 2019-04-29 06:12
浏览 96

如何根据输入字段触发add_action('woocommerce_cart_calculate_fees')(复选框)[复制]

This question is an exact duplicate of:

Problem: Add_action code determines if "food" category in cart and applies delivery fee. Works perfectly but before fee applied, need customer to check if catering order needs delivery. If true, add fee.

Goal is to determine if "food" in cart," which current code does, and if true, show checkbox labelled Deliver Catering Order? [ ]. If true, adds fee on same row in cart before totals.

I worked on code to add row to Cart before totals but get fatal error. If I get add row code working, can I insert into add_action custom fee code after the loop through cart but before condition to apply fee.


        add_action( 'woocommerce_cart_calculate_fees','custom_pcat_fee', 20, 1 );
        function custom_pcat_fee( $cart ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

        // Set HERE your categories (can be term IDs, slugs or names) in a coma separated array
        $categories = array('food');
        $fee_amount = 0;

        // Loop through cart items
        foreach( $cart->get_cart() as $cart_item ){
        if( has_term( $categories, 'product_cat', $cart_item['product_id']) )
            $fee_amount = 25;
    }

        // Adding the fee
        if ( $fee_amount > 0 ){
        // Last argument is related to enable tax (true or false)
        WC()->cart->add_fee( __( "Delivery Fee", "woocommerce" ), $fee_amount, 
false );
    }
}

I expect the action to determine if "food" slug in cart, and if true, add row to cart before totals with customer input box to indicate if order delivery. If true, $25 fee added to same new row?

</div>
  • 写回答

1条回答 默认 最新

  • douzhenqun1271 2019-04-29 09:40
    关注
    add_action( 'woocommerce_cart_calculate_fees',function($cart) {      
    
        if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
    
        $is_food = false;
        foreach ( $cart->cart_contents as $item ) {
            if ( $item['data']->is_type( 'food' ) ) {
                $is_food = true;
                break;
            }
        }
        if($is_food){
           $fee=25;
           $cart->add_fee( 'Delivery Fee',$fee, true, 'standard' );     
        }
    });
    

    Please try above code by pasting it into functions.php of a child theme.

    评论

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示