在store 中,产品的价格是根据用户在产品页面上提交的"长度"字段来计算的.由于这个长度是重要的信息,我想显示提交的长度也在购物车,在 checkout 和发票审查订单.
我已经成功地将该字段添加到购物车中,但如何才能将其添加到审查订单和发票中的购物车项目中?(甚至在整个过程中提到的每个产品中).是否有我可以使用的滤镜或操作?那又是怎么做的呢?我找不到吗?
我有以下(相关)代码:
// Get custom field value Length, calculate new item price, save it as custom cart item data
add_filter('woocommerce_add_cart_item_data', 'add_custom_field_data', 20, 2 );
function add_custom_field_data( $cart_item_data, $product_id ){
if (! isset($_POST['length']))
return $cart_item_data;
$length = (float) sanitize_text_field( $_POST['length'] );
if( empty($length) )
return $cart_item_data;
$product = wc_get_product($product_id); // The WC_Product Object
$base_price = (float) $product->get_regular_price(); // Product reg price
// New price calculation
$new_price = (($base_price * $length)/1000)+1.90;
// Set the custom amount in cart object
$cart_item_data['custom_data']['extra_charge'] = (float) $length;
$cart_item_data['custom_data']['new_price'] = (float) $new_price;
$cart_item_data['custom_data']['unique_key'] = md5( microtime() . rand() ); // Make each item unique
return $cart_item_data;
}
// Set the new calculated cart item price
add_action( 'woocommerce_before_calculate_totals', 'new_price_add_length', 20, 1 );
function new_price_add_length( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
foreach ( $cart->get_cart() as $cart_item ) {
if( isset($cart_item['custom_data']['new_price']) )
$cart_item['data']->set_price( (float) $cart_item['custom_data']['new_price'] );
}
}
//Add length to product in cart
add_action( 'woocommerce_after_cart_item_name', 'wmw_display_length', 20 );
function wmw_display_length( $cart_item ) {
if( isset($cart_item['custom_data']['extra_charge']) ) {
$length = $cart_item['custom_data']['extra_charge'];
echo '<dl class="variation"><dt class="variation-Length">Length(mm):</dt><dd class="variation-Length"><p>' . $cart_item['custom_data']['extra_charge'] . '</dd></dl>';
}
}
您知道如何在其他位置/屏幕上获取这些数据吗?