从 Woocommerce 3 中的 GET 变量设置自定义购物车商品价格值

Set a custom cart item price value from a GET variable In Woocommerce 3

我的 Woocommerce 网站上有一个功能,允许客户根据我通过 URL 传递的值设置自定义金额以支付特定产品。

我正在使用 woocommerce_before_calculate_totals 挂钩,在我升级到 WC 3.3.5 之前,它工作正常。现在,当我 运行 代码时,结帐最初会显示自定义金额。

但是,加载程序完成更新后,会将价格重置为“0”(即在结帐页面的总字段中显示 £0.00)。

这是代码:

add_action( 'woocommerce_before_calculate_totals', 'pay_custom_amount', 99);

function pay_custom_amount() {
    $payment_value = $_GET['amount'];

    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {

        if($cart_item['data']->id == 21 ){
            $cart_item['data']->set_price($payment_value);
        }
    }
}

好吧,让我感到困惑。我已经在 Stack Overflow 上搜索了解决方案,但看不到任何类似的问题。我多次看到钩子 运行s 但我认为这是正常的。

如果有人知道这里可能发生了什么,如果你能分享就太好了。

您无法从 URL 获取价格并将其设置在 woocommerce_before_calculate_totals 操作挂钩中。这需要以不同的方式进行。

在下面的代码中:

  • 第一个挂钩函数将从 URl 中获取 "amount" 并将其设置(注册)在购物车项目对象中作为自定义数据。
  • 第二个挂钩函数将从自定义购物车项目数据中读取该金额并将其设置为新价格。

Now your the target product ID in your code need to be the same ID that the added to cart product.

代码:

// Get the custom "amount" from URL and save it as custom data to the cart item
add_filter( 'woocommerce_add_cart_item_data', 'add_pack_data_to_cart_item_data', 20, 2 );
function add_pack_data_to_cart_item_data( $cart_item_data, $product_id ){
    if( ! isset($_GET['amount']) )
        return $cart_item_data;

    $amount = esc_attr( $_GET['amount'] );
    if( empty($amount) )
        return $cart_item_data;

    // Set the custom amount in cart object
    $cart_item_data['custom_price'] = (float) $amount;
    $cart_item_data['unique_key'] = md5( microtime() . rand() ); // Make each item unique

    return $cart_item_data;
}

// Alter conditionally cart item price based on product ID and custom registered "amount"
add_action( 'woocommerce_before_calculate_totals', 'change_conditionally_cart_item_price', 30, 1 );
function change_conditionally_cart_item_price( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // HERE set your targeted product ID
    $targeted_product_id = 21;

    foreach ( $cart->get_cart() as $cart_item ) {
        // Checking for the targeted product ID and the registered "amount" cart item custom data to set the new price
        if($cart_item['data']->get_id() == $targeted_product_id && isset($cart_item['custom_price']) )
            $cart_item['data']->set_price($cart_item['custom_price']);
    }
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。 已测试并有效。