在Woocommerce中,我使用jQuery
来计算单个产品页面上的自定义价格,现在需要将此值传递到购物车。
所需的行为是将从隐藏字段检索到的新价格传递到购物车项目价格。
下面是我的实际代码:
// Hidden input field in single product page
add_action( 'woocommerce_before_add_to_cart_button', 'custom_hidden_product_field', 11, 0 );
function custom_hidden_product_field() {
echo '<input type="hidden" id="hidden_field" name="custom_price" class="custom_price" value="">';
}
// The code to pass this data to the cart:
add_action( 'woocommerce_add_cart_item_data', 'save_custom_fields_data_to_cart', 10, 2 );
function save_custom_fields_data_to_cart( $cart_item_data, $product_id ) {
if( ! empty( $_REQUEST['custom_price'] ) ) {
// Set the custom data in the cart item
$cart_item_data['custom_data']['custom_price'] = $_REQUEST['custom_price'];
$data = array( 'custom_price' => $_REQUEST['custom_price'] );
// below statement make sure every add to cart action as unique line item
$cart_item_data['custom_data']['unique_key'] = md5( microtime().rand() );
WC()->session->set( 'custom_data', $data );
}
return $cart_item_data;
}
然后检查$data
和$cart_item_data
,查看它们是否都返回在页面上计算的custom_price
数据。
但是,我去查看购物车,行项目的值仍然是0。
我设置var
等于WC()->session->set( 'custom_data', $data );
,然后var_dump
检查它,但这返回NULL
,这可能就是它返回的,我不完全确定,因为我从来没有使用过它。
我还应该补充一下,我将产品后端中的regular_price
设置为0。当我删除这个(并将其留空)时,我会返回错误:
Copyright © 2018 - 2019 www.wp-cn.com All Rights Reserved.粤ICP备15017999号-1
我想知道我是否错过了什么,如果有人能借一些光到这里?谢谢
1条答案
按热度按时间ao218c7q1#
更新2021-处理迷你购物车中的自定义价格项目
首先,出于测试目的,我们在隐藏的输入字段中添加价格,因为您没有给予计算价格的代码:
然后,您将使用以下命令更改购物车商品价格 *(不需要 *
WC_Session
):代码放在活动子主题(或活动主题)的functions.php文件中。测试和作品。