最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

functions - Problems adding a new field to product in cart

programmeradmin1浏览0评论

I have a problem and it is that I need to add a new field in the product form, and that I can obtain it in the cart page and also in the checkout. After trying it on my own, I decided to googling a bit. The fact is that I found someone who had something similar to what I want, so I decided to approve and this is the code which I place in "functions.php":

function add_text_field() { ?>
 <div class="new-field-wrap">
 <label for="new-field"><?php _e( 'Custom data', 'pc' ); ?></label>
 <input type="text" name='new-field' id='new-field' value=''>
 </div>
<?php }
add_action( 'woocommerce_before_add_to_cart_button', 'add_text_field' );

function add_to_cart_validation( $passed, $product_id, $quantity, $variation_id=null ) {
 if( empty( $_POST['new-field'] ) ) {
 $passed = false;
 wc_add_notice( __( 'Your name is a required field.', 'pc' ), 'error' );
 }
 return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'add_to_cart_validation', 10, 4 );

function add_cart_item_data( $cart_item_data, $product_id, $variation_id ) {
 if( isset( $_POST['new-field'] ) ) {
 $cart_item_data['new-field'] = sanitize_text_field( $_POST['new-field'] );
 }
 return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'add_cart_item_data', 10, 3 );

function get_item_data( $item_data, $cart_item_data ) {
 if( isset( $cart_item_data['new-field'] ) ) {
 $item_data[] = array(
 'key' => __( 'Custom data', 'pc' ),
 'value' => wc_clean( $cart_item_data['new-field'] )
 );
 }
 return $item_data;
}
add_filter( 'woocommerce_get_item_data', 'get_item_data', 10, 2 );

function checkout_create_order_line_item( $item, $cart_item_key, $values, $order ) {
 if( isset( $values['new-field'] ) ) {
 $item->add_meta_data(
 __( 'Custom data', 'pc' ),
 $values['new-field'],
 true
 );
 }
}
add_action( 'woocommerce_checkout_create_order_line_item', 'checkout_create_order_line_item', 10, 4 );

There is a filter for validation. And it ALWAYS throws the validation error, as if the field did not exist in the form, or did not take its value when clicking add to cart. I don't know how to remedy this anymore, since I can't find an explanation. Anyone who knows what could be happening?

发布评论

评论列表(0)

  1. 暂无评论