要使其按您想要的方式工作,请尝试以下代码,您的产品说明将显示在产品页面下面的产品元。在我的代码中,我在“添加到购物车”窗体中添加了一个隐藏字段,一些jquery代码会将文本区域字段的内容即时添加到隐藏字段中。这样,产品说明就可以作为自定义数据保存在购物车项目中。
现在,这个答案将不会处理按顺序保存数据并在签出后显示数据的问题,因为这对于这个问题来说既不明确,也不太宽泛。
// 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'];
}