根据 URL 查询变量向 WooCommerce Total Cart 添加费用

问题描述 投票:0回答:1

在以下代码中,我向 WooCommerce Total Cart 添加百分比费用,但

IF
语句中的条件不起作用。我以某种方式检查了一切。

// Adding Nutritionist Fees
add_action('woocommerce_cart_calculate_fees', 'custom_nutritionist_fee');

function custom_nutritionist_fee() {
    $chec = (isset($_GET['diet']) && esc_attr( $_GET['diet'] ) == 'Nutritionist') ? 1 : 0;
    print($chec);

    if (isset($_GET['diet']) && esc_attr( $_GET['diet'] ) == 'Nutritionist') {
     $percentage = 0.25;
    $percentage_fee = (WC()->cart->get_cart_contents_total() + WC()->cart->get_shipping_total()) * $percentage;
    // Add the fee to the cart
    WC()->cart->add_fee(__('Nutritionist Fees', 'txtdomain'), $percentage_fee);
    }
//  return;
}

但是 IF 语句始终为假。

php wordpress woocommerce cart fee
1个回答
0
投票

您需要首先在 WC Session 变量中添加查询字符串值(逻辑)。然后您可以使用 WC 会话变量来启用/禁用您的自定义“营养师”费用。

尝试以下操作:

add_action('template_redirect', 'set_diet_query_string_value_to_wc_session');
function set_diet_query_string_value_to_wc_session() {
    if ( isset($_GET['diet']) && ! empty($_GET['diet']) ) {
        WC()->session->set('nutritionist_fee', strval($_GET['diet']) === 'Nutritionist' ? true : false);
    }
}

// Adding Nutritionist Fees
add_action('woocommerce_cart_calculate_fees', 'custom_nutritionist_fee');
function custom_nutritionist_fee( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( WC()->session->get('nutritionist_fee') ) {
        $fee_rate   = 0.25;
        $fee_amount = ($cart->get_cart_contents_total() + $cart->get_shipping_total()) * $fee_rate;
        // Add the fee to the cart
        $cart->add_fee(__('Nutritionist Fees', 'txtdomain'), $fee_amount);
    }
}

代码位于子主题的functions.php 文件中(或插件中)。已测试并有效。

© www.soinside.com 2019 - 2024. All rights reserved.