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

时间:2019-04-29 06:12:39

标签: php wordpress woocommerce cart hook-woocommerce

问题:添加操作代码确定购物车中的“食品”类别是否适用,并收取送货费。效果很好,但在收取费用之前,需要客户检查餐饮订单是否需要交付。如果为true,请加收费用。

目标是确定购物车中的“食物”是否符合当前代码的要求,如果为true,则显示标记为“交付餐饮订单”的复选框?[]。如果为true,则在总计之前在购物车的同一行添加费用。

我研究过在总计之前将行添加到购物车的代码,但出现致命错误。如果我可以使用添加行代码,可以在购物车循环之后但在申请费用的条件之前插入add_action自定义费用代码。


        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 );
    }
}

我希望该操作确定“食物”是否在购物车中,如果为true,则在总计前加客户输入框的行中向购物车中添加行,以指示订单是否已交付。如果为true,则将$ 25费用添加到同一新行吗?

1 个答案:

答案 0 :(得分:0)

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' );     
    }
});

请尝试将上述代码粘贴到子主题的functions.php中。