Custom Text field for custom product in woocommerce
if ( ! function_exists( 'yith_wc_custom_input_text' ) ) {
/**
* Display input text before add to cart button. */
function yith_wc_custom_input_text() {
global $product;
$product_id = $product ? $product->get_id() : 0;
$products_to_show = array( 2874, 28 );
if ( $product_id && in_array( $product_id, $products_to_show ) ) {
$label = __( 'Write your comments', 'yith-wc-input-text' );
printf( '', esc_html( $label ) );
}
}
add_action( 'woocommerce_before_add_to_cart_button', 'yith_wc_custom_input_text' );
}
if ( ! function_exists( 'yith_wc_add_cart_item_data' ) ) {
/**
* Add the input text value - item data.
* @param array $cart_item_data cart item data.
* @param integer $product_id product id.
* @param integer $variation_id variation id.
* @param boolean $quantity quantity
*/
function yith_wc_add_cart_item_data( $cart_item_data, $product_id, $variation_id, $quantity ) {
if ( ! empty( $_POST['yith_wc_input_text'] ) ) {
$cart_item_data['yith_wc_input_text'] = sanitize_text_field( wp_unslash( $_POST['yith_wc_input_text'] ) );
}
return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'yith_wc_add_cart_item_data', 10, 4 );
}
if ( ! function_exists( 'yith_wc_get_item_data' ) ) {
function yith_wc_get_item_data( $cart_data, $cart_item ) {
if ( ! empty( $cart_item['yith_wc_input_text'] ) ) {
$cart_data[] = array('name'=> esc_html__( 'Your comments', 'yith-wc-input-text' ), 'display' => $cart_item['yith_wc_input_text'], );
}
return $cart_data;
}
add_filter( 'woocommerce_get_item_data', 'yith_wc_get_item_data', 25, 2 );
}
if ( ! function_exists( 'yith_wc_order_line_item' ) ) {
/** * Add the input text to the order. */
function yith_wc_order_line_item( $item, $cart_item_key, $values, $order ) {
foreach ( $item as $cart_item_key => $data ) {
if ( isset( $data['yith_wc_input_text'] ) ) {
$item->add_meta_data( 'your_comments', $data['yith_wc_input_text'], true );
}
}
}
add_action( 'woocommerce_checkout_create_order_line_item', 'yith_wc_order_line_item', 10, 4 );
}
if ( ! function_exists( 'yith_wc_add_inline_styles' ) ) {
/** * Add CSS style */
function yith_wc_add_inline_styles() {
$styles = ".yith_wc_input_text__wrapper { display: flex; flex-direction: column; margin: 20px 0px; }.yith_wc_input_text__wrapper .yith_wc_input_text__field{ max-width: 220px; margin-top:8px;}";
wp_add_inline_style( 'woocommerce-inline', $styles );
}
add_action( 'wp_enqueue_scripts', 'yith_wc_add_inline_styles' );
}