WooCommerce: Add input field to every item in cart

There is a wordpress plugin called WC Fields Factory for the exact purpose.

You can also achieve this by using the following woocommerce hooks woocommerce_before_add_to_cart_button, woocommerce_add_to_cart, woocommerce_cart_item_name,and 'woocommerce_add_order_item_meta'

like for adding text field to product page

function add_name_on_tshirt_field() {
  echo '<table class="variations" cellspacing="0">
      <tbody>
          <tr>
          <td class="label"><label for="color">Name On T-Shirt</label></td>
          <td class="value">
              <input type="text" name="name-on-tshirt" value="" />
          </td>
      </tr>                             
      </tbody>
  </table>';
}
add_action( 'woocommerce_before_add_to_cart_button', 'add_name_on_tshirt_field' );

For displaying custom field on cart item table use the below

function render_meta_on_cart_item( $title = null, $cart_item = null, $cart_item_key = null ) {
    if( $cart_item_key && is_cart() ) {
        echo $title. '<dl class="">
                 <dt class="">Name On T-Shirt : </dt>
                 <dd class=""><p>'. WC()->session->get( $cart_item_key.'_name_on_tshirt') .'</p></dd>           
              </dl>';
    }else {
        echo $title;
    }
}
add_filter( 'woocommerce_cart_item_name', 'render_meta_on_cart_item', 1, 3 );

to make your custom meta data on you order details, do some thing like this

function tshirt_order_meta_handler( $item_id, $values, $cart_item_key ) {
    wc_add_order_item_meta( $item_id, "name_on_tshirt", WC()->session->get( $cart_item_key.'_name_on_tshirt') );    
}
add_action( 'woocommerce_add_order_item_meta', 'tshirt_order_meta_handler', 1, 3 );

for detailed implementation, i have an article about how to do this without using any plugins. http://sarkware.com/how-to-pass-custom-data-to-cart-line-item-in-woocommerce-without-using-plugins/

Leave a Comment