Php 在WooCommerce中通过Url变量(GET)应用费用

Php 在WooCommerce中通过Url变量(GET)应用费用,php,wordpress,woocommerce,get,hook-woocommerce,Php,Wordpress,Woocommerce,Get,Hook Woocommerce,我试图将“添加费用”值带到查看订单页面,但它不起作用 我需要启用我的签出页面以等待url参数“getfee” 如果getfee等于2,则添加费用 如果没有,那么不要添加任何内容 这是我的密码: add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' ); function woocommerce_custom_surcharge() { global $woocommerce; i

我试图将“添加费用”值带到查看订单页面,但它不起作用

我需要启用我的签出页面以等待url参数“getfee”

如果getfee等于2,则添加费用

如果没有,那么不要添加任何内容

这是我的密码:

add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge() {
    global $woocommerce;

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;
    
    $fee = $_GET["getfee"];

    if( $fee == "2") {
        $percentage = 0.01;
        $surcharge = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total ) * $percentage;    
        $woocommerce->cart->add_fee( 'Surcharge', $surcharge, true, '' );
    }
}
到目前为止,它在结帐页面中添加了费用,但在查看订单时,却没有显示

我认为这可能是因为签出页面没有该参数,但不确定


非常感谢您的帮助。

您需要在WC会话变量中设置Url费用以避免此问题:

// Get URL variable and set it to a WC Session variable
add_action( 'template_redirect', 'getfee_to_wc_session' );
function getfee_to_wc_session() {
    if ( isset($_GET['getfee']) ) {
        WC()->session->set('getfee', esc_attr($_GET['getfee']));
    }
}

// Add a percentage fee
add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    $fee = WC()->session->get('getfee'); // Get WC session variable value

    if( $fee == "2") {
        $percentage = 0.01;
        $surcharge = ( $cart->cart_contents_total + $cart->shipping_total ) * $percentage;
        $cart->add_fee( 'Surcharge', $surcharge, true, '' );
    }
}

代码进入活动子主题(或活动主题)的functions.php文件。已测试并正常工作。

是的,每次再次计算购物车内容总数时都会调用此函数。您需要以某种方式传递此参数,例如,将其存储到签出页面上的会话中,以便在订单审阅页面上再次调用此函数时可以从该会话访问它。