商店中的产品价格是根据用户在产品页面上提交的“长度”字段计算的。由于这个长度是重要信息,我想在购物车中显示提交的长度,在结帐和发票中查看订单。
我已成功将该字段添加到购物车,但如何将其添加到审核订单和发票中的购物车项目中? (甚至在整个过程中提到的每个产品中)。我可以使用过滤器或操作吗?如何?我没找到?
我有以下(相关)代码:
// 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>';
}
}
有什么想法如何在其他位置/屏幕上获取这些数据吗?
您需要添加以下内容才能在订单和发票上显示您的“长度”:
// Save and display the Length (custom order item metadata)
add_action( 'woocommerce_checkout_create_order_line_item', 'save_order_item_custom_meta_data', 10, 4 );
function save_order_item_custom_meta_data( $item, $cart_item_key, $values, $order ) {
if( isset($values['custom_data']['extra_charge']) ) {
$item->update_meta_data( 'length', $values['custom_data']['extra_charge'] );
}
}
// Add readable "meta key" label name replacement
add_filter('woocommerce_order_item_display_meta_key', 'filter_wc_order_item_display_meta_key', 10, 3 );
function filter_wc_order_item_display_meta_key( $display_key, $meta, $item ) {
if( $item->get_type() === 'line_item' && $meta->key === 'length' ) {
$display_key = __('Length(mm)', 'woocommerce' );
}
return $display_key;
}
代码位于子主题的functions.php 文件中(或插件中)。已测试并工作。