要使其按您的意愿工作,请尝试以下代码,您的产品说明将显示在产品元下方的产品页面中。在我的代码中,我在添加到购物车表单中添加了一个隐藏字段,一些 jQuery 代码会即时将 textarea 字段的内容添加到隐藏字段中。这样,产品备注可以在购物车项目中保存为自定义数据。
现在这个答案将无法处理按顺序保存数据并在结帐后显示它,因为这对于这个问题来说并不明确且过于宽泛。
// Add a custom product note below product meta in single product pages
add_action('woocommerce_single_product_summary', 'custom_product_note', 100 );
function custom_product_note() {
echo '<br><div>';
woocommerce_form_field('customer_note', array(
'type' => 'textarea',
'class' => array( 'my-field-class form-row-wide') ,
'label' => __('Product note') ,
'placeholder' => __('Add your note here, please…') ,
'required' => false,
) , '');
echo '</div>';
//
?>
<script type="text/javascript">
jQuery( function($){
$('#customer_note').on( 'input blur', function() {
$('#product_note').val($(this).val());
});
});
</script>
<?php
}
// Custom hidden field in add to cart form
add_action( 'woocommerce_before_add_to_cart_button', 'hidden_field_before_add_to_cart_button', 5 );
function hidden_field_before_add_to_cart_button(){
echo '<input type="hidden" name="product_note" id="product_note" value="">';
}
// Add customer note to cart item data
add_filter( 'woocommerce_add_cart_item_data', 'add_product_note_to_cart_item_data', 20, 2 );
function add_product_note_to_cart_item_data( $cart_item_data, $product_id ){
if( isset($_POST['product_note']) && ! empty($_POST['product_note']) ){
$product_note = sanitize_textarea_field( $_POST['product_note'] );
$cart_item_data['product_note'] = $product_note;
}
return $cart_item_data;
}
代码进入您的活动子主题(或活动主题)的 function.php 文件中。经过测试并且可以工作。
如果您想在添加到购物车按钮后显示此字段,您将使用以下更短的代码:
// Add a custom product note after add to cart button in single product pages
add_action('woocommerce_after_add_to_cart_button', 'custom_product_note', 10 );
function custom_product_note() {
echo '<br><div>';
woocommerce_form_field('product_note', array(
'type' => 'textarea',
'class' => array( 'my-field-class form-row-wide') ,
'label' => __('Product note') ,
'placeholder' => __('Add your note here, please…') ,
'required' => false,
) , '');
echo '</div>';
}
// Add customer note to cart item data
add_filter( 'woocommerce_add_cart_item_data', 'add_product_note_to_cart_item_data', 20, 2 );
function add_product_note_to_cart_item_data( $cart_item_data, $product_id ){
if( isset($_POST['product_note']) && ! empty($_POST['product_note']) ){
$product_note = sanitize_textarea_field( $_POST['product_note'] );
$cart_item_data['product_note'] = $product_note;
}
return $cart_item_data;
}
代码进入您的活动子主题(或活动主题)的 function.php 文件中。经过测试并且可以工作。
可以通过以下方式访问此自定义购物车商品数据:
foreach( WC()->cart->get_cart() as $cart_item ){
if( isset($cart_item['product_note']) )
echo $cart_item['product_note'];
}