Add custom field in products to display in cart, checkout and in ordersHow do I pass multiple custom fields to cart in Woocommerce?wordpress simple paypal shopping cart shortcode in custom fieldsGet all posts from Wordpress as JSONWordpress Woocommerce Pass a product name through hard coded URL to the cart and checkoutCustomize add to cartSet product custom field and display value in cart, checkout and view orderLink “name-your-price” with “add_to_cart” shortcode woocommerceWoocommerce override Product Price with custom value on cart and checkoutWoocommerce: Custom price based on user input - Mini cart conflictAdd custom fields as cart item meta and order item meta in WooCommerceChange main price when add to cart using opencart2.3

Is there a maximum distance from a planet that a moon can orbit?

3D Crossword, Cryptic, Statue View & Maze

Is this one of the engines from the 9/11 aircraft?

Given a cell in a Voronoi diagram, which point did it come from?

What does "play with your toy’s toys" mean?

If you snatch, I trade

What does the hyphen "-" mean in "tar xzf -"?

Does this Wild Magic result affect the sorcerer or just other creatures?

What is this tool/thing in an Aztec painting?

Fedora boot screen shows both Fedora logo and Lenovo logo. Why and How?

Why do some professors with PhDs leave their professorships to teach high school?

How much will studying magic in an academy cost?

Java TreeMap.floorKey() equivalent for std::map

I am completely new to Tales from the Floating Vagabond, how do I get started?

How do I turn off a repeating trade?

Can Ogre clerics use Purify Food and Drink on humanoid characters?

First-year PhD giving a talk among well-established researchers in the field

Can we put equal sign after aggregate functions in sql?

Did the CIA blow up a Siberian pipeline in 1982?

Hot coffee brewing solutions for deep woods camping

How to make clear to people I don't want to answer their "Where are you from?" question?

Links to webpages in books

What is the legal status of travelling with methadone in your carry-on?

Long term BTC investing



Add custom field in products to display in cart, checkout and in orders


How do I pass multiple custom fields to cart in Woocommerce?wordpress simple paypal shopping cart shortcode in custom fieldsGet all posts from Wordpress as JSONWordpress Woocommerce Pass a product name through hard coded URL to the cart and checkoutCustomize add to cartSet product custom field and display value in cart, checkout and view orderLink “name-your-price” with “add_to_cart” shortcode woocommerceWoocommerce override Product Price with custom value on cart and checkoutWoocommerce: Custom price based on user input - Mini cart conflictAdd custom fields as cart item meta and order item meta in WooCommerceChange main price when add to cart using opencart2.3






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I am using a Custom post type and integrated woocommerce on it, I am able to add an add-to-cart button on the pages and can add it to cart, so it works fine



here is my code



class WCCPT_Product_Data_Store_CPT extends WC_Product_Data_Store_CPT 

/**
* Method to read a product from the database.
* @param WC_Product
*/

public function read( &$product ) ! in_array( $post_object->post_type, array( 'products', 'product' ) ) ) // change birds with your post type
throw new Exception( __( 'Invalid product.', 'woocommerce' ) );


$id = $product->get_id();

$product->set_props( array(
'name' => $post_object->post_title,
'slug' => $post_object->post_name,
'date_created' => 0 < $post_object->post_date_gmt ? wc_string_to_timestamp( $post_object->post_date_gmt ) : null,
'date_modified' => 0 < $post_object->post_modified_gmt ? wc_string_to_timestamp( $post_object->post_modified_gmt ) : null,
'status' => $post_object->post_status,
'description' => $post_object->post_content,
'short_description' => $post_object->post_excerpt,
'parent_id' => $post_object->post_parent,
'menu_order' => $post_object->menu_order,
'reviews_allowed' => 'open' === $post_object->comment_status,
) );

$this->read_attributes( $product );
$this->read_downloads( $product );
$this->read_visibility( $product );
$this->read_product_data( $product );
$this->read_extra_data( $product );
$product->set_object_read( true );


/**
* Get the product type based on product ID.
*
* @since 3.0.0
* @param int $product_id
* @return bool

add_filter( 'woocommerce_data_stores', 'woocommerce_data_stores' );

function woocommerce_data_stores ( $stores )
$stores['product'] = 'WCCPT_Product_Data_Store_CPT';
return $stores;


add_filter('woocommerce_product_get_price', 'woocommerce_product_get_price', 10, 2 );
function woocommerce_product_get_price( $price, $product )

$reflector = new ReflectionClass($product);
$classProperty = $reflector->getProperty('id');
$classProperty->setAccessible(true);
$vid_id = $classProperty->getValue($product);
//$cpt_product_price = get_field('product_specifications', $vid_id);
$cpt_product_price = get_field('e-commerce', $vid_id);

if ($product->get_id() == $vid_id)
$price = $cpt_product_price['global']['price'];


return $price;


//add_filter('the_content','rei_add_to_cart_button', 20,1);
/*
function rei_add_to_cart_button($content)
global $post;
if ($post->post_type !== 'products') return $content;
var_dump($content);


$cpt_product_price = get_field('product_specifications', get_the_ID());
//var_dump($cpt_product_price);


ob_start();
if ( !empty($cpt_product_price['_price']) )
?>
<form action="" method="post">
<input name="add-to-cart" type="hidden" value="<?php echo $post->ID ?>" />
<input name="quantity" type="number" value="1" min="1" />
<input name="submit" type="submit" value="Add to cart" />
</form>
<?php

return $content . ob_get_clean();


*/




function rei_add_to_cart_button()
global $post;
if ($post->post_type !== 'products') return;
//var_dump($content);



$get_ecommerce = get_field('e-commerce', get_the_ID());
//var_dump($get_ecommerce);

$get_ecommerce_price = $get_ecommerce['global']['price'];

//global

//price

//$cpt_product_price = get_field('product_specifications', get_the_ID());


//var_dump($cpt_product_price);
//var_dump($cpt_product_price);

ob_start();
if ( !empty($get_ecommerce_price) )
?>
<form action="" method="post">
<input name="_gram" type="hidden" value="10">
<input name="add-to-cart" type="hidden" value="<?php echo $post->ID ?>" />
<input name="quantity" type="number" value="1" min="1" />
<input name="submit" type="submit" value="Add to cart" />
</form>
<?php

return ob_get_clean();



but now I need to add some custom fields on the product page, a dropdown containing colours "black" and "white", this is just an ordinary dropdown. How can I when I select a value it will display on the cart under the product name



enter image description here



enter image description here










share|improve this question






























    1















    I am using a Custom post type and integrated woocommerce on it, I am able to add an add-to-cart button on the pages and can add it to cart, so it works fine



    here is my code



    class WCCPT_Product_Data_Store_CPT extends WC_Product_Data_Store_CPT 

    /**
    * Method to read a product from the database.
    * @param WC_Product
    */

    public function read( &$product ) ! in_array( $post_object->post_type, array( 'products', 'product' ) ) ) // change birds with your post type
    throw new Exception( __( 'Invalid product.', 'woocommerce' ) );


    $id = $product->get_id();

    $product->set_props( array(
    'name' => $post_object->post_title,
    'slug' => $post_object->post_name,
    'date_created' => 0 < $post_object->post_date_gmt ? wc_string_to_timestamp( $post_object->post_date_gmt ) : null,
    'date_modified' => 0 < $post_object->post_modified_gmt ? wc_string_to_timestamp( $post_object->post_modified_gmt ) : null,
    'status' => $post_object->post_status,
    'description' => $post_object->post_content,
    'short_description' => $post_object->post_excerpt,
    'parent_id' => $post_object->post_parent,
    'menu_order' => $post_object->menu_order,
    'reviews_allowed' => 'open' === $post_object->comment_status,
    ) );

    $this->read_attributes( $product );
    $this->read_downloads( $product );
    $this->read_visibility( $product );
    $this->read_product_data( $product );
    $this->read_extra_data( $product );
    $product->set_object_read( true );


    /**
    * Get the product type based on product ID.
    *
    * @since 3.0.0
    * @param int $product_id
    * @return bool

    add_filter( 'woocommerce_data_stores', 'woocommerce_data_stores' );

    function woocommerce_data_stores ( $stores )
    $stores['product'] = 'WCCPT_Product_Data_Store_CPT';
    return $stores;


    add_filter('woocommerce_product_get_price', 'woocommerce_product_get_price', 10, 2 );
    function woocommerce_product_get_price( $price, $product )

    $reflector = new ReflectionClass($product);
    $classProperty = $reflector->getProperty('id');
    $classProperty->setAccessible(true);
    $vid_id = $classProperty->getValue($product);
    //$cpt_product_price = get_field('product_specifications', $vid_id);
    $cpt_product_price = get_field('e-commerce', $vid_id);

    if ($product->get_id() == $vid_id)
    $price = $cpt_product_price['global']['price'];


    return $price;


    //add_filter('the_content','rei_add_to_cart_button', 20,1);
    /*
    function rei_add_to_cart_button($content)
    global $post;
    if ($post->post_type !== 'products') return $content;
    var_dump($content);


    $cpt_product_price = get_field('product_specifications', get_the_ID());
    //var_dump($cpt_product_price);


    ob_start();
    if ( !empty($cpt_product_price['_price']) )
    ?>
    <form action="" method="post">
    <input name="add-to-cart" type="hidden" value="<?php echo $post->ID ?>" />
    <input name="quantity" type="number" value="1" min="1" />
    <input name="submit" type="submit" value="Add to cart" />
    </form>
    <?php

    return $content . ob_get_clean();


    */




    function rei_add_to_cart_button()
    global $post;
    if ($post->post_type !== 'products') return;
    //var_dump($content);



    $get_ecommerce = get_field('e-commerce', get_the_ID());
    //var_dump($get_ecommerce);

    $get_ecommerce_price = $get_ecommerce['global']['price'];

    //global

    //price

    //$cpt_product_price = get_field('product_specifications', get_the_ID());


    //var_dump($cpt_product_price);
    //var_dump($cpt_product_price);

    ob_start();
    if ( !empty($get_ecommerce_price) )
    ?>
    <form action="" method="post">
    <input name="_gram" type="hidden" value="10">
    <input name="add-to-cart" type="hidden" value="<?php echo $post->ID ?>" />
    <input name="quantity" type="number" value="1" min="1" />
    <input name="submit" type="submit" value="Add to cart" />
    </form>
    <?php

    return ob_get_clean();



    but now I need to add some custom fields on the product page, a dropdown containing colours "black" and "white", this is just an ordinary dropdown. How can I when I select a value it will display on the cart under the product name



    enter image description here



    enter image description here










    share|improve this question


























      1












      1








      1


      1






      I am using a Custom post type and integrated woocommerce on it, I am able to add an add-to-cart button on the pages and can add it to cart, so it works fine



      here is my code



      class WCCPT_Product_Data_Store_CPT extends WC_Product_Data_Store_CPT 

      /**
      * Method to read a product from the database.
      * @param WC_Product
      */

      public function read( &$product ) ! in_array( $post_object->post_type, array( 'products', 'product' ) ) ) // change birds with your post type
      throw new Exception( __( 'Invalid product.', 'woocommerce' ) );


      $id = $product->get_id();

      $product->set_props( array(
      'name' => $post_object->post_title,
      'slug' => $post_object->post_name,
      'date_created' => 0 < $post_object->post_date_gmt ? wc_string_to_timestamp( $post_object->post_date_gmt ) : null,
      'date_modified' => 0 < $post_object->post_modified_gmt ? wc_string_to_timestamp( $post_object->post_modified_gmt ) : null,
      'status' => $post_object->post_status,
      'description' => $post_object->post_content,
      'short_description' => $post_object->post_excerpt,
      'parent_id' => $post_object->post_parent,
      'menu_order' => $post_object->menu_order,
      'reviews_allowed' => 'open' === $post_object->comment_status,
      ) );

      $this->read_attributes( $product );
      $this->read_downloads( $product );
      $this->read_visibility( $product );
      $this->read_product_data( $product );
      $this->read_extra_data( $product );
      $product->set_object_read( true );


      /**
      * Get the product type based on product ID.
      *
      * @since 3.0.0
      * @param int $product_id
      * @return bool

      add_filter( 'woocommerce_data_stores', 'woocommerce_data_stores' );

      function woocommerce_data_stores ( $stores )
      $stores['product'] = 'WCCPT_Product_Data_Store_CPT';
      return $stores;


      add_filter('woocommerce_product_get_price', 'woocommerce_product_get_price', 10, 2 );
      function woocommerce_product_get_price( $price, $product )

      $reflector = new ReflectionClass($product);
      $classProperty = $reflector->getProperty('id');
      $classProperty->setAccessible(true);
      $vid_id = $classProperty->getValue($product);
      //$cpt_product_price = get_field('product_specifications', $vid_id);
      $cpt_product_price = get_field('e-commerce', $vid_id);

      if ($product->get_id() == $vid_id)
      $price = $cpt_product_price['global']['price'];


      return $price;


      //add_filter('the_content','rei_add_to_cart_button', 20,1);
      /*
      function rei_add_to_cart_button($content)
      global $post;
      if ($post->post_type !== 'products') return $content;
      var_dump($content);


      $cpt_product_price = get_field('product_specifications', get_the_ID());
      //var_dump($cpt_product_price);


      ob_start();
      if ( !empty($cpt_product_price['_price']) )
      ?>
      <form action="" method="post">
      <input name="add-to-cart" type="hidden" value="<?php echo $post->ID ?>" />
      <input name="quantity" type="number" value="1" min="1" />
      <input name="submit" type="submit" value="Add to cart" />
      </form>
      <?php

      return $content . ob_get_clean();


      */




      function rei_add_to_cart_button()
      global $post;
      if ($post->post_type !== 'products') return;
      //var_dump($content);



      $get_ecommerce = get_field('e-commerce', get_the_ID());
      //var_dump($get_ecommerce);

      $get_ecommerce_price = $get_ecommerce['global']['price'];

      //global

      //price

      //$cpt_product_price = get_field('product_specifications', get_the_ID());


      //var_dump($cpt_product_price);
      //var_dump($cpt_product_price);

      ob_start();
      if ( !empty($get_ecommerce_price) )
      ?>
      <form action="" method="post">
      <input name="_gram" type="hidden" value="10">
      <input name="add-to-cart" type="hidden" value="<?php echo $post->ID ?>" />
      <input name="quantity" type="number" value="1" min="1" />
      <input name="submit" type="submit" value="Add to cart" />
      </form>
      <?php

      return ob_get_clean();



      but now I need to add some custom fields on the product page, a dropdown containing colours "black" and "white", this is just an ordinary dropdown. How can I when I select a value it will display on the cart under the product name



      enter image description here



      enter image description here










      share|improve this question
















      I am using a Custom post type and integrated woocommerce on it, I am able to add an add-to-cart button on the pages and can add it to cart, so it works fine



      here is my code



      class WCCPT_Product_Data_Store_CPT extends WC_Product_Data_Store_CPT 

      /**
      * Method to read a product from the database.
      * @param WC_Product
      */

      public function read( &$product ) ! in_array( $post_object->post_type, array( 'products', 'product' ) ) ) // change birds with your post type
      throw new Exception( __( 'Invalid product.', 'woocommerce' ) );


      $id = $product->get_id();

      $product->set_props( array(
      'name' => $post_object->post_title,
      'slug' => $post_object->post_name,
      'date_created' => 0 < $post_object->post_date_gmt ? wc_string_to_timestamp( $post_object->post_date_gmt ) : null,
      'date_modified' => 0 < $post_object->post_modified_gmt ? wc_string_to_timestamp( $post_object->post_modified_gmt ) : null,
      'status' => $post_object->post_status,
      'description' => $post_object->post_content,
      'short_description' => $post_object->post_excerpt,
      'parent_id' => $post_object->post_parent,
      'menu_order' => $post_object->menu_order,
      'reviews_allowed' => 'open' === $post_object->comment_status,
      ) );

      $this->read_attributes( $product );
      $this->read_downloads( $product );
      $this->read_visibility( $product );
      $this->read_product_data( $product );
      $this->read_extra_data( $product );
      $product->set_object_read( true );


      /**
      * Get the product type based on product ID.
      *
      * @since 3.0.0
      * @param int $product_id
      * @return bool

      add_filter( 'woocommerce_data_stores', 'woocommerce_data_stores' );

      function woocommerce_data_stores ( $stores )
      $stores['product'] = 'WCCPT_Product_Data_Store_CPT';
      return $stores;


      add_filter('woocommerce_product_get_price', 'woocommerce_product_get_price', 10, 2 );
      function woocommerce_product_get_price( $price, $product )

      $reflector = new ReflectionClass($product);
      $classProperty = $reflector->getProperty('id');
      $classProperty->setAccessible(true);
      $vid_id = $classProperty->getValue($product);
      //$cpt_product_price = get_field('product_specifications', $vid_id);
      $cpt_product_price = get_field('e-commerce', $vid_id);

      if ($product->get_id() == $vid_id)
      $price = $cpt_product_price['global']['price'];


      return $price;


      //add_filter('the_content','rei_add_to_cart_button', 20,1);
      /*
      function rei_add_to_cart_button($content)
      global $post;
      if ($post->post_type !== 'products') return $content;
      var_dump($content);


      $cpt_product_price = get_field('product_specifications', get_the_ID());
      //var_dump($cpt_product_price);


      ob_start();
      if ( !empty($cpt_product_price['_price']) )
      ?>
      <form action="" method="post">
      <input name="add-to-cart" type="hidden" value="<?php echo $post->ID ?>" />
      <input name="quantity" type="number" value="1" min="1" />
      <input name="submit" type="submit" value="Add to cart" />
      </form>
      <?php

      return $content . ob_get_clean();


      */




      function rei_add_to_cart_button()
      global $post;
      if ($post->post_type !== 'products') return;
      //var_dump($content);



      $get_ecommerce = get_field('e-commerce', get_the_ID());
      //var_dump($get_ecommerce);

      $get_ecommerce_price = $get_ecommerce['global']['price'];

      //global

      //price

      //$cpt_product_price = get_field('product_specifications', get_the_ID());


      //var_dump($cpt_product_price);
      //var_dump($cpt_product_price);

      ob_start();
      if ( !empty($get_ecommerce_price) )
      ?>
      <form action="" method="post">
      <input name="_gram" type="hidden" value="10">
      <input name="add-to-cart" type="hidden" value="<?php echo $post->ID ?>" />
      <input name="quantity" type="number" value="1" min="1" />
      <input name="submit" type="submit" value="Add to cart" />
      </form>
      <?php

      return ob_get_clean();



      but now I need to add some custom fields on the product page, a dropdown containing colours "black" and "white", this is just an ordinary dropdown. How can I when I select a value it will display on the cart under the product name



      enter image description here



      enter image description here







      php wordpress woocommerce product custom-post-type






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 25 at 12:45









      LoicTheAztec

      104k15 gold badges81 silver badges121 bronze badges




      104k15 gold badges81 silver badges121 bronze badges










      asked Mar 25 at 8:56









      Francis Alvin TanFrancis Alvin Tan

      3641 gold badge7 silver badges21 bronze badges




      3641 gold badge7 silver badges21 bronze badges






















          1 Answer
          1






          active

          oldest

          votes


















          1














          Update 2



          Try the following (that normally adds a dropdown in single product pages and save/display the selected value in cart item):



          // Frontend: custom select field (dropdown) in product single pages
          add_action( 'woocommerce_before_add_to_cart_button', 'fabric_length_product_field' );
          function fabric_length_product_field()
          global $product;

          // Select field
          woocommerce_form_field('fitting_color', array(
          'type' => 'select',
          'class' => array('my-field-class form-row-wide'),
          'label' => __('_fitting_color', 'woocommerce'),
          'required' => true, // or false
          'options' => array(
          '' => __('Select a color', 'woocommerce'),
          'black' => __('Black', 'woocommerce'),
          'white' => __('White', 'woocommerce'),
          ),
          ),'');


          // Add "fitting_color" selected value as custom cart item data
          add_filter( 'woocommerce_add_cart_item_data', 'add_custom_cart_item_data', 20, 2 );
          function add_custom_cart_item_data( $cart_item_data, $product_id )
          if( isset($_POST['fitting_color']) && ! empty($_POST['fitting_color']))
          $cart_item_data['fcolor']= array(
          'value' => esc_attr($_POST['fitting_color']),
          'unique_key' => md5( microtime() . rand() ), // <= Make each cart item unique
          );

          return $cart_item_data;



          // Display custom cart item data in cart and checkout pages
          add_filter( 'woocommerce_get_item_data', 'display_custom_cart_item_data', 10, 2 );
          function display_custom_cart_item_data( $cart_item_data, $cart_item )
          if ( isset( $cart_item['fcolor']['value'] ) )
          $cart_item_data[] = array(
          'name' => __( 'Fitting color', 'woocommerce' ),
          'value' => $cart_item['fcolor']['value'],
          );

          return $cart_item_data;



          Code goes on function.php file of your active child theme (or active theme). It should works.




          For save/display on order (and display on email notifications), you will use:



          // Save chosen slelect field value to each order item as custom meta data and display it everywhere
          add_action('woocommerce_checkout_create_order_line_item', 'save_order_item_product_fitting_color', 10, 4 );
          function save_order_item_product_fitting_color( $item, $cart_item_key, $values, $order )
          if( isset($values['fcolor']['value']) )
          $key = __('Fitting color', 'woocommerce');
          $value = $values['fcolor']['value'];
          $item->update_meta_data( $key, $value );





          And the missing field validation:



          // Field validation
          add_filter( 'woocommerce_add_to_cart_validation', 'dropdown_fitting_color_validation', 10, 3 );
          function dropdown_fitting_color_validation( $passed, $product_id, $quantity )
          if( isset($_POST['fitting_color']) && empty($_POST['fitting_color']) )
          wc_add_notice( __( "Please select a Fitting color", "woocommerce" ), 'error' );
          return false;


          return $passed;






          share|improve this answer

























          • Hi @loicTheAztec, its working fine on a regular woo products, but not working on a custom post type page

            – Francis Alvin Tan
            Mar 25 at 13:28











          • I think i got it working now on CPT, i just removed the first action ( add_action( 'woocommerce_before_add_to_cart_button', 'fabric_length_product_field' ); ) and included this function (fabric_length_product_field()) inside the add to cart form

            – Francis Alvin Tan
            Mar 25 at 13:34













          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55334203%2fadd-custom-field-in-products-to-display-in-cart-checkout-and-in-orders%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          Update 2



          Try the following (that normally adds a dropdown in single product pages and save/display the selected value in cart item):



          // Frontend: custom select field (dropdown) in product single pages
          add_action( 'woocommerce_before_add_to_cart_button', 'fabric_length_product_field' );
          function fabric_length_product_field()
          global $product;

          // Select field
          woocommerce_form_field('fitting_color', array(
          'type' => 'select',
          'class' => array('my-field-class form-row-wide'),
          'label' => __('_fitting_color', 'woocommerce'),
          'required' => true, // or false
          'options' => array(
          '' => __('Select a color', 'woocommerce'),
          'black' => __('Black', 'woocommerce'),
          'white' => __('White', 'woocommerce'),
          ),
          ),'');


          // Add "fitting_color" selected value as custom cart item data
          add_filter( 'woocommerce_add_cart_item_data', 'add_custom_cart_item_data', 20, 2 );
          function add_custom_cart_item_data( $cart_item_data, $product_id )
          if( isset($_POST['fitting_color']) && ! empty($_POST['fitting_color']))
          $cart_item_data['fcolor']= array(
          'value' => esc_attr($_POST['fitting_color']),
          'unique_key' => md5( microtime() . rand() ), // <= Make each cart item unique
          );

          return $cart_item_data;



          // Display custom cart item data in cart and checkout pages
          add_filter( 'woocommerce_get_item_data', 'display_custom_cart_item_data', 10, 2 );
          function display_custom_cart_item_data( $cart_item_data, $cart_item )
          if ( isset( $cart_item['fcolor']['value'] ) )
          $cart_item_data[] = array(
          'name' => __( 'Fitting color', 'woocommerce' ),
          'value' => $cart_item['fcolor']['value'],
          );

          return $cart_item_data;



          Code goes on function.php file of your active child theme (or active theme). It should works.




          For save/display on order (and display on email notifications), you will use:



          // Save chosen slelect field value to each order item as custom meta data and display it everywhere
          add_action('woocommerce_checkout_create_order_line_item', 'save_order_item_product_fitting_color', 10, 4 );
          function save_order_item_product_fitting_color( $item, $cart_item_key, $values, $order )
          if( isset($values['fcolor']['value']) )
          $key = __('Fitting color', 'woocommerce');
          $value = $values['fcolor']['value'];
          $item->update_meta_data( $key, $value );





          And the missing field validation:



          // Field validation
          add_filter( 'woocommerce_add_to_cart_validation', 'dropdown_fitting_color_validation', 10, 3 );
          function dropdown_fitting_color_validation( $passed, $product_id, $quantity )
          if( isset($_POST['fitting_color']) && empty($_POST['fitting_color']) )
          wc_add_notice( __( "Please select a Fitting color", "woocommerce" ), 'error' );
          return false;


          return $passed;






          share|improve this answer

























          • Hi @loicTheAztec, its working fine on a regular woo products, but not working on a custom post type page

            – Francis Alvin Tan
            Mar 25 at 13:28











          • I think i got it working now on CPT, i just removed the first action ( add_action( 'woocommerce_before_add_to_cart_button', 'fabric_length_product_field' ); ) and included this function (fabric_length_product_field()) inside the add to cart form

            – Francis Alvin Tan
            Mar 25 at 13:34















          1














          Update 2



          Try the following (that normally adds a dropdown in single product pages and save/display the selected value in cart item):



          // Frontend: custom select field (dropdown) in product single pages
          add_action( 'woocommerce_before_add_to_cart_button', 'fabric_length_product_field' );
          function fabric_length_product_field()
          global $product;

          // Select field
          woocommerce_form_field('fitting_color', array(
          'type' => 'select',
          'class' => array('my-field-class form-row-wide'),
          'label' => __('_fitting_color', 'woocommerce'),
          'required' => true, // or false
          'options' => array(
          '' => __('Select a color', 'woocommerce'),
          'black' => __('Black', 'woocommerce'),
          'white' => __('White', 'woocommerce'),
          ),
          ),'');


          // Add "fitting_color" selected value as custom cart item data
          add_filter( 'woocommerce_add_cart_item_data', 'add_custom_cart_item_data', 20, 2 );
          function add_custom_cart_item_data( $cart_item_data, $product_id )
          if( isset($_POST['fitting_color']) && ! empty($_POST['fitting_color']))
          $cart_item_data['fcolor']= array(
          'value' => esc_attr($_POST['fitting_color']),
          'unique_key' => md5( microtime() . rand() ), // <= Make each cart item unique
          );

          return $cart_item_data;



          // Display custom cart item data in cart and checkout pages
          add_filter( 'woocommerce_get_item_data', 'display_custom_cart_item_data', 10, 2 );
          function display_custom_cart_item_data( $cart_item_data, $cart_item )
          if ( isset( $cart_item['fcolor']['value'] ) )
          $cart_item_data[] = array(
          'name' => __( 'Fitting color', 'woocommerce' ),
          'value' => $cart_item['fcolor']['value'],
          );

          return $cart_item_data;



          Code goes on function.php file of your active child theme (or active theme). It should works.




          For save/display on order (and display on email notifications), you will use:



          // Save chosen slelect field value to each order item as custom meta data and display it everywhere
          add_action('woocommerce_checkout_create_order_line_item', 'save_order_item_product_fitting_color', 10, 4 );
          function save_order_item_product_fitting_color( $item, $cart_item_key, $values, $order )
          if( isset($values['fcolor']['value']) )
          $key = __('Fitting color', 'woocommerce');
          $value = $values['fcolor']['value'];
          $item->update_meta_data( $key, $value );





          And the missing field validation:



          // Field validation
          add_filter( 'woocommerce_add_to_cart_validation', 'dropdown_fitting_color_validation', 10, 3 );
          function dropdown_fitting_color_validation( $passed, $product_id, $quantity )
          if( isset($_POST['fitting_color']) && empty($_POST['fitting_color']) )
          wc_add_notice( __( "Please select a Fitting color", "woocommerce" ), 'error' );
          return false;


          return $passed;






          share|improve this answer

























          • Hi @loicTheAztec, its working fine on a regular woo products, but not working on a custom post type page

            – Francis Alvin Tan
            Mar 25 at 13:28











          • I think i got it working now on CPT, i just removed the first action ( add_action( 'woocommerce_before_add_to_cart_button', 'fabric_length_product_field' ); ) and included this function (fabric_length_product_field()) inside the add to cart form

            – Francis Alvin Tan
            Mar 25 at 13:34













          1












          1








          1







          Update 2



          Try the following (that normally adds a dropdown in single product pages and save/display the selected value in cart item):



          // Frontend: custom select field (dropdown) in product single pages
          add_action( 'woocommerce_before_add_to_cart_button', 'fabric_length_product_field' );
          function fabric_length_product_field()
          global $product;

          // Select field
          woocommerce_form_field('fitting_color', array(
          'type' => 'select',
          'class' => array('my-field-class form-row-wide'),
          'label' => __('_fitting_color', 'woocommerce'),
          'required' => true, // or false
          'options' => array(
          '' => __('Select a color', 'woocommerce'),
          'black' => __('Black', 'woocommerce'),
          'white' => __('White', 'woocommerce'),
          ),
          ),'');


          // Add "fitting_color" selected value as custom cart item data
          add_filter( 'woocommerce_add_cart_item_data', 'add_custom_cart_item_data', 20, 2 );
          function add_custom_cart_item_data( $cart_item_data, $product_id )
          if( isset($_POST['fitting_color']) && ! empty($_POST['fitting_color']))
          $cart_item_data['fcolor']= array(
          'value' => esc_attr($_POST['fitting_color']),
          'unique_key' => md5( microtime() . rand() ), // <= Make each cart item unique
          );

          return $cart_item_data;



          // Display custom cart item data in cart and checkout pages
          add_filter( 'woocommerce_get_item_data', 'display_custom_cart_item_data', 10, 2 );
          function display_custom_cart_item_data( $cart_item_data, $cart_item )
          if ( isset( $cart_item['fcolor']['value'] ) )
          $cart_item_data[] = array(
          'name' => __( 'Fitting color', 'woocommerce' ),
          'value' => $cart_item['fcolor']['value'],
          );

          return $cart_item_data;



          Code goes on function.php file of your active child theme (or active theme). It should works.




          For save/display on order (and display on email notifications), you will use:



          // Save chosen slelect field value to each order item as custom meta data and display it everywhere
          add_action('woocommerce_checkout_create_order_line_item', 'save_order_item_product_fitting_color', 10, 4 );
          function save_order_item_product_fitting_color( $item, $cart_item_key, $values, $order )
          if( isset($values['fcolor']['value']) )
          $key = __('Fitting color', 'woocommerce');
          $value = $values['fcolor']['value'];
          $item->update_meta_data( $key, $value );





          And the missing field validation:



          // Field validation
          add_filter( 'woocommerce_add_to_cart_validation', 'dropdown_fitting_color_validation', 10, 3 );
          function dropdown_fitting_color_validation( $passed, $product_id, $quantity )
          if( isset($_POST['fitting_color']) && empty($_POST['fitting_color']) )
          wc_add_notice( __( "Please select a Fitting color", "woocommerce" ), 'error' );
          return false;


          return $passed;






          share|improve this answer















          Update 2



          Try the following (that normally adds a dropdown in single product pages and save/display the selected value in cart item):



          // Frontend: custom select field (dropdown) in product single pages
          add_action( 'woocommerce_before_add_to_cart_button', 'fabric_length_product_field' );
          function fabric_length_product_field()
          global $product;

          // Select field
          woocommerce_form_field('fitting_color', array(
          'type' => 'select',
          'class' => array('my-field-class form-row-wide'),
          'label' => __('_fitting_color', 'woocommerce'),
          'required' => true, // or false
          'options' => array(
          '' => __('Select a color', 'woocommerce'),
          'black' => __('Black', 'woocommerce'),
          'white' => __('White', 'woocommerce'),
          ),
          ),'');


          // Add "fitting_color" selected value as custom cart item data
          add_filter( 'woocommerce_add_cart_item_data', 'add_custom_cart_item_data', 20, 2 );
          function add_custom_cart_item_data( $cart_item_data, $product_id )
          if( isset($_POST['fitting_color']) && ! empty($_POST['fitting_color']))
          $cart_item_data['fcolor']= array(
          'value' => esc_attr($_POST['fitting_color']),
          'unique_key' => md5( microtime() . rand() ), // <= Make each cart item unique
          );

          return $cart_item_data;



          // Display custom cart item data in cart and checkout pages
          add_filter( 'woocommerce_get_item_data', 'display_custom_cart_item_data', 10, 2 );
          function display_custom_cart_item_data( $cart_item_data, $cart_item )
          if ( isset( $cart_item['fcolor']['value'] ) )
          $cart_item_data[] = array(
          'name' => __( 'Fitting color', 'woocommerce' ),
          'value' => $cart_item['fcolor']['value'],
          );

          return $cart_item_data;



          Code goes on function.php file of your active child theme (or active theme). It should works.




          For save/display on order (and display on email notifications), you will use:



          // Save chosen slelect field value to each order item as custom meta data and display it everywhere
          add_action('woocommerce_checkout_create_order_line_item', 'save_order_item_product_fitting_color', 10, 4 );
          function save_order_item_product_fitting_color( $item, $cart_item_key, $values, $order )
          if( isset($values['fcolor']['value']) )
          $key = __('Fitting color', 'woocommerce');
          $value = $values['fcolor']['value'];
          $item->update_meta_data( $key, $value );





          And the missing field validation:



          // Field validation
          add_filter( 'woocommerce_add_to_cart_validation', 'dropdown_fitting_color_validation', 10, 3 );
          function dropdown_fitting_color_validation( $passed, $product_id, $quantity )
          if( isset($_POST['fitting_color']) && empty($_POST['fitting_color']) )
          wc_add_notice( __( "Please select a Fitting color", "woocommerce" ), 'error' );
          return false;


          return $passed;







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 25 at 13:00

























          answered Mar 25 at 12:44









          LoicTheAztecLoicTheAztec

          104k15 gold badges81 silver badges121 bronze badges




          104k15 gold badges81 silver badges121 bronze badges












          • Hi @loicTheAztec, its working fine on a regular woo products, but not working on a custom post type page

            – Francis Alvin Tan
            Mar 25 at 13:28











          • I think i got it working now on CPT, i just removed the first action ( add_action( 'woocommerce_before_add_to_cart_button', 'fabric_length_product_field' ); ) and included this function (fabric_length_product_field()) inside the add to cart form

            – Francis Alvin Tan
            Mar 25 at 13:34

















          • Hi @loicTheAztec, its working fine on a regular woo products, but not working on a custom post type page

            – Francis Alvin Tan
            Mar 25 at 13:28











          • I think i got it working now on CPT, i just removed the first action ( add_action( 'woocommerce_before_add_to_cart_button', 'fabric_length_product_field' ); ) and included this function (fabric_length_product_field()) inside the add to cart form

            – Francis Alvin Tan
            Mar 25 at 13:34
















          Hi @loicTheAztec, its working fine on a regular woo products, but not working on a custom post type page

          – Francis Alvin Tan
          Mar 25 at 13:28





          Hi @loicTheAztec, its working fine on a regular woo products, but not working on a custom post type page

          – Francis Alvin Tan
          Mar 25 at 13:28













          I think i got it working now on CPT, i just removed the first action ( add_action( 'woocommerce_before_add_to_cart_button', 'fabric_length_product_field' ); ) and included this function (fabric_length_product_field()) inside the add to cart form

          – Francis Alvin Tan
          Mar 25 at 13:34





          I think i got it working now on CPT, i just removed the first action ( add_action( 'woocommerce_before_add_to_cart_button', 'fabric_length_product_field' ); ) and included this function (fabric_length_product_field()) inside the add to cart form

          – Francis Alvin Tan
          Mar 25 at 13:34



















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55334203%2fadd-custom-field-in-products-to-display-in-cart-checkout-and-in-orders%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

          155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해