我在WooCommerce中设置了一个自定义计算器作为新插件 .
从这个计算器,我通过我的总价格和总数量 . 价格是通过计算产品的总平方英寸(它是一块布)并乘以订购的总件数来计算的 .
但我们根据总磅数对运费进行定价,并将其设定为0.003 / sq英寸 . 因此,为了正确计算运费,我需要将此信息传递给购物车 . 为了清楚起见,我需要将布料的总平方英寸传递到购物车,然后根据此价格对其进行定价 .
我已经通过使用隐藏值字段和以下代码将数量和价格添加到购物车:
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'] && $_REQUEST['custom_quantity'] ) ) {
// Set the custom data in the cart item
if($_REQUEST['custom_price'] < 25) {
$cart_item_data['custom_price'] = 25.00;
} else {
$cart_item_data['custom_price'] = $_REQUEST['custom_price'];
}
// Set the custom data in the cart item
$cart_item_data['custom_quantity'] = $_REQUEST['custom_quantity'];
// Make each item as a unique separated cart item
$cart_item_data['unique_key'] = md5( microtime().rand() );
}
return $cart_item_data;
}
但是我遇到了以下代码的问题:
add_action( 'woocommerce_before_calculate_totals', 'change_cart_item_price', 30, 1 );
function change_cart_item_price( $cart ) {
if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) )
return;
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item ) {
// Set the new price
if( isset($cart_item['custom_price']) ){
$cart_item['data']->set_price($cart_item['custom_price']);
}
//set the new quantity
if( isset($cart_item['custom_quantity']) ) {
$cart_item['data']->set_quantity($cart_item['custom_quantity']);
}
}
}
价格过得很好,但是当代码点击下面的部分时:
if( isset($cart_item['custom_quantity']) ) {
$cart_item['data']->set_quantity($cart_item['custom_quantity']);
}
它失败并导致网站崩溃 . 特别是这条线
$cart_item['data']->set_quantity($cart_item['custom_quantity']);
我知道这是因为我跑了一个快速的 echo "good"
并且它通过了很好 .
我错误地使用了 set_quantity
吗?