您的代码中存在大量错误和缺失的内容
1)设置:
If you want to display correctly the label “Name On T-Shirt” on customer Orders and email notifications, you need to create an attribute for this label name (under Products > Attributes):
创建产品属性:
为此属性添加一些值:
和……
然后保存…
2)守则:
// Add the custom field to product pages
add_action( 'woocommerce_before_add_to_cart_button', 'add_nmy_custom_product_field', 10, 0 );
function add_nmy_custom_product_field() {
?>
}
// Save the custom product field data in Cart item
add_action( 'woocommerce_add_cart_item_data', 'save_in_cart_my_custom_product_field', 10, 2 );
function save_in_cart_my_custom_product_field( $cart_item_data, $product_id ) {
if( isset( $_POST['name-on-tshirt'] ) ) {
$cart_item_data[ 'name-on-tshirt' ] = $_POST['name-on-tshirt'];
// When add to cart action make an unique line item
$cart_item_data['unique_key'] = md5( microtime().rand() );
WC()->session->set( 'custom_data', $_POST['name-on-tshirt'] );
}
return $cart_item_data;
}
// Render the custom product field in cart and checkout
add_filter( 'woocommerce_get_item_data', 'render_custom_field_meta_on_cart_and_checkout', 10, 2 );
function render_custom_field_meta_on_cart_and_checkout( $cart_data, $cart_item ) {
$custom_items = array();
if( !empty( $cart_data ) )
$custom_items = $cart_data;
if( $custom_field_value = $cart_item['name-on-tshirt'] )
$custom_items[] = array(
'name' => __( 'Name On T-Shirt', 'woocommerce' ),
'value' => $custom_field_value,
'display' => $custom_field_value,
);
return $custom_items;
}
// Add the the custom product field as item meta data in the order
add_action( 'woocommerce_add_order_item_meta', 'tshirt_order_meta_handler', 10, 3 );
function tshirt_order_meta_handler( $item_id, $cart_item, $cart_item_key ) {
$custom_field_value = $cart_item['name-on-tshirt'];
if( ! empty($custom_field_value) )
wc_update_order_item_meta( $item_id, 'pa_name-on-tshirt', $custom_field_value );
}
此代码位于活动子主题(或主题)的function.php文件中,或者也可以放在任何插件文件中.
此代码适用于WooCommerce版本,测试范围为2.5到3.0