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?
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745106767a4611604.html
评论列表(0条)