一旦 URL 更改,您的 GET 变量就会丢失,因此所有产品价格都为空,因为您也没有针对已添加到购物车的产品。
在这种情况下,当检测到custom_p GET 变量时,您需要启用并使用 WooCommerce 会话变量来存储产品 ID 和自定义价格。然后您可以使用该 WooCommerce Session 变量来更改产品价格。
首先我们检测必要的数据并将其存储在WC_Session 变量中:
// get and set the custom product price in WC_Session
add_action( 'init', 'get_custom_product_price_set_to_session' );
function get_custom_product_price_set_to_session() {
// Check that there is a 'custom_p' GET variable
if( isset($_GET['add-to-cart']) && isset($_GET['custom_p'])
&& $_GET['custom_p'] > 0 && $_GET['add-to-cart'] > 0 ) {
// Enable customer WC_Session (needed on first add to cart)
if ( ! WC()->session->has_session() ) {
WC()->session->set_customer_session_cookie( true );
}
// Set the product_id and the custom price in WC_Session variable
WC()->session->set('custom_p', [
'id' => (int) wc_clean($_GET['add-to-cart']),
'price' => (float) wc_clean($_GET['custom_p']),
]);
}
}
那么有两种方法可以改变加入购物车的产品价格(只能选择一种)
选项 1 - 直接更改产品价格:
// Change product price from WC_Session data
add_filter('woocommerce_product_get_price', 'custom_product_price', 900, 2 );
add_filter('woocommerce_product_get_regular_price', 'custom_product_price', 900, 2 );
add_filter('woocommerce_product_variation_get_price', 'custom_product_price', 900, 2 );
add_filter('woocommerce_product_variation_get_regular_price', 'custom_product_price', 900, 2 );
function custom_product_price( $price, $product ) {
if ( ( $data = WC()->session->get('custom_p') ) && $product->get_id() == $data['id'] ) {
$price = $data['price'];
}
return $price;
}
选项 2 - 更改购物车商品价格:
// Change cart item price from WC_Session data
add_action( 'woocommerce_before_calculate_totals', 'custom_cart_item_price', 20, 1 );
function custom_cart_item_price( $cart ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Must be required since Woocommerce version 3.2 for cart items properties changes
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Looo through our specific cart item keys
foreach ( $cart->get_cart() as $cart_item ) {
// Get custom product price for the current item
if ( ( $data = WC()->session->get('custom_p') ) && $cart_item['data']->get_id() == $data['id'] ) {
// Set the new product price
$cart_item['data']->set_price( $data['price'] );
}
}
}
代码在您的活动子主题(或活动主题)的functions.php 文件中。经过测试并且可以工作。
USAGE URL 变量示例:www.example.com/?add-to-cart=37&custom_p=75