您使用的代码没有将任何商品传递到购物车,它只是显示现有的自定义购物车商品数据。
要从其他产品字段或其他相关内容添加自定义购物车项目数据,您将使用类似 (例如,在单个产品页面上需要一些额外字段):
add_filter( 'woocommerce_add_cart_item_data', 'add_custom_cart_item_data', 10, 3 );
function add_custom_cart_item_data($cart_item_data, $product_id, $variation_id ){
if( isset( $_POST['product_field1'] ) ) {
$cart_item_data['custom_data'][1] = sanitize_text_field( $_POST['product_field1'] );
}
if( isset( $_POST['product_field2'] ) ) {
$cart_item_data['custom_data'][2] = sanitize_text_field( $_POST['product_field2'] );
}
return $cart_item_data;
}
现在在购物车和结帐页面中显示该自定义购物车商品数据:
add_filter( 'woocommerce_get_item_data', 'display_enrolment_text_cart', 10, 2 );
function display_enrolment_text_cart( $item_data, $cart_item ) {
if ( isset($cart_item['enrolmentName']) && ! empty($cart_item['enrolmentName']) ) {
$item_data[] = array(
'key' => __( 'Enrolment', 'test' ),
'value' => wc_clean( $cart_item['enrolmentName'] ),
'display' => '',
);
}
// Additional displayed custom cat item data
if ( isset($cart_item['custom_data'][1]) && ! empty($cart_item['custom_data'][1]) ) {
$item_data[] = array(
'key' => __( 'Field 1', 'test' ),
'value' => wc_clean( $cart_item['custom_data'][1] ),
'display' => '',
);
}
if ( isset($cart_item['custom_data'][2]) && ! empty($cart_item['custom_data'][2]) ) {
$item_data[] = array(
'key' => __( 'Field 2', 'test' ),
'value' => wc_clean( $cart_item['custom_data'][2] ),
'display' => '',
);
}
return $item_data;
}
代码进入您的活动子主题(或活动主题)的 function.php 文件中。它应该可以工作。
相关话题: Store custom data using WC_Cart add_to_cart() method in Woocommerce 3
相关完整线程: Add custom field in products to display in cart, checkout and in orders