Saving a product custom field and displaying it in cart page

With WooCommerce and I am doing some customization in my functions.php file, to get a custom field value on Cart page.

I add a custom field before add to cart:

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' );

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;
    }

  /*  $d=WC();
    echo "<pre>";
    print_r($d);*/
}
add_filter( 'woocommerce_cart_item_name', 'render_meta_on_cart_item', 1, 3 );


function tshirt_order_meta_handler( $item_id, $values, $cart_item_key ) {
/*  echo "<pre>";
    print_r($item_id)*/;
    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 );

And i want this custom value on cart page i also used hook

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );

But I can’t get any value for this custom field.

How it’s possible? What I am doing wrong?

Thanks

Read more here: Saving a product custom field and displaying it in cart page

Leave a Reply

Your email address will not be published. Required fields are marked *