Search

How to Add Custom Data to WooCommerce Order

    Akshaya Rane
Listen to this article

WooCommerce Add Custom data

I work with the WooCommerce plugin and I work on customizing it. I have repeatedly observed on various discussion forums and Q&A forums that adding custom data to the WooCommerce order is always a point of contention.

However, these discussions are so specific to a certain step in the process that the entire picture is never made clear to the readers.

So, I am writing this post to help you accomplish your goal in 6 simple steps, and believe me the task is not as daunting as it seems. By the end of the post, I am confident that adding custom data to WooCommerce sessions should not be a hassle for you ever again.

(Heads up: Here I shall be talking about adding custom data to WooCommerce orders before WooCommerce v3.0. For version 3.0 and above, find the solution here!)

To make it easy for you to understand, I will be using a use-case scenario. If you have custom requirements and are not sure about the solution in this post, reach out to here to discuss your requirements for Free. Our Official WooCommerce experts will develop a custom solution for you!

Nevertheless, you can apply the solution for whatever your requirements may be.

So here’s what I had to do.

Note: User input was required in a custom video template design site. The user adds this data and then clicks ‘Add to Cart’. This user input should then be displayed on the cart and checkout page. To achieve this objective I had to add the user’s custom data to a WooCommerce session

Table of Contents :

Benefits of Adding Custom Data to WooCommerce Orders

Adding custom data to WooCommerce orders isn’t just a technical tweak—it can genuinely make a big difference for both your store and your customers. Here’s how:

  1. Better Customer Experience: Imagine getting a personalized note or special instructions with your order. It’s those small touches that can make customers feel special and appreciated.
  2. Smoother Order Management: Adding extra fields like delivery instructions or product customization requests makes it easier for your team to manage orders accurately and quickly.
  3. Clearer Communication: If a customer leaves special delivery instructions, they’ll go straight to the shipping team, ensuring nothing gets lost in translation.
    Useful Insights: Collecting more detailed info about your customers helps you understand their preferences better, leading to smarter business decisions.
  4. Automated Processes: Custom data fields can kickstart automated workflows or emails, like sending gift-wrapping instructions to the packing team, making everything run more smoothly.

Methods of Adding Custom Data to WooCommerce Orders

There are several ways to add custom data to WooCommerce orders. Here’s a quick overview:

  1. Using Plugins: Plugins are the easiest way to add custom data. They often have user-friendly interfaces that let you add extra fields to WooCommerce orders without needing to code.
  2. Custom Fields in Product Pages: You can add custom fields directly to your WooCommerce product pages. This allows customers to enter their data, which then gets carried over to the order details during checkout.
  3. Custom Checkout Fields: Adding custom fields to the checkout page is another method. This can be done using WooCommerce hooks and filters to capture additional information from customers when they place an order.

These methods make it simple to incorporate custom data into WooCommerce orders, enhancing the functionality of your store and improving customer experience.

Adding Custom Data to a WooCommerce Order Programmatically (Step-by-Step Guide)

Now that we’ve covered why adding custom data is important and the benefits it brings, let’s look at how you can actually implement this in your WooCommerce store. Here are the steps to add custom data to a WooCommerce order:

add custom data WooCommerce Product

 

Product Page

Step 1: Add Data in a Custom Session, on the ‘Add to Cart’ Button Click

For those of you who have worked with WooCommerce might know that on the click of the ‘Add to Cart’ button, the product page gets refreshed and the user data is lost. Hence, we should add the custom data from our product page to a custom session created using Ajax. This code is invoked before the WooCommerce session is created.

<?php
add_action('wp_ajax_wdm_add_user_custom_data_options', 'wdm_add_user_custom_data_options_callback');
add_action('wp_ajax_nopriv_wdm_add_user_custom_data_options', 'wdm_add_user_custom_data_options_callback');

function wdm_add_user_custom_data_options_callback()
{
      //Custom data - Sent Via AJAX post method
      $product_id = $_POST['id']; //This is product ID
      $user_custom_data_values =  $_POST['user_data']; //This is User custom value sent via AJAX
      session_start();
      $_SESSION['wdm_user_custom_data'] = $user_custom_data_values;
      die();
}

?>

Step 2: Add Custom Data in WooCommerce Session

At this step, the WooCommerce session has been created and is now available for us to add our custom data. We use the following code to add the custom data from the session we have created into the WooCommerce session. At this step, our session is also unsetsince the data in it has been captured and it is not needed anymore.

add_filter('woocommerce_add_cart_item_data','wdm_add_item_data',1,4);  
 
if(!function_exists('wdm_add_item_data'))
{
    function wdm_add_item_data($cart_item_data,$product_id, $variation_id, $quantity )
    {
        /*Here, We are adding item in WooCommerce session with, wdm_user_custom_data_value name*/
        global $woocommerce;
        session_start();    
        if (isset($_SESSION['wdm_user_custom_data'])) {
            $option = $_SESSION['wdm_user_custom_data'];       
            $new_value = array('wdm_user_custom_data_value' => $option);
        }
        if(empty($option))
            return $cart_item_data;
        else
        {    
            if(empty($cart_item_data))
                return $new_value;
            else
                return array_merge($cart_item_data,$new_value);
        }
        unset($_SESSION['wdm_user_custom_data']); 
        //Unset our custom session variable, as it is no longer needed.
    }
}

Step 3: Extract Custom Data from WooCommerce Session and Insert it into Cart Object

At this stage, we have default product details along with the custom data in the WooCommerce session. The default data gets added to the cart object owing to the functionality provided by the plugin. However, we need to explicitly extract the custom data from the WooCommerce session and insert it into the cart object. This can be implemented with the following code.

add_filter('woocommerce_get_cart_item_from_session', 'wdm_get_cart_items_from_session', 1, 3 );
if(!function_exists('wdm_get_cart_items_from_session'))
{
    function wdm_get_cart_items_from_session($item,$values,$key)
    {
        if (array_key_exists( 'wdm_user_custom_data_value', $values ) )
        {
        $item['wdm_user_custom_data_value'] = $values['wdm_user_custom_data_value'];
        }       
        return $item;
    }
}

Does this feel overwhelming? Let WooCommerce experts help you with a solution quickly.  Get In Touch

Step 4: Display User Custom Data on the Cart and Checkout page

Now that we have our custom data in the cart object all we need to do now is to display this data in the Cart and the Checkout page. This is how your cart page should look after the custom data has been added from the WooCommerce session to your Cart.

My-Cart-Page

 

Cart Page

add_filter('woocommerce_checkout_cart_item_quantity','wdm_add_user_custom_option_from_session_into_cart',1,3);  
add_filter('woocommerce_cart_item_price','wdm_add_user_custom_option_from_session_into_cart',1,3);
if(!function_exists('wdm_add_user_custom_option_from_session_into_cart'))
{
 function wdm_add_user_custom_option_from_session_into_cart($product_name, $values, $cart_item_key )
    {
        /*code to add custom data on Cart & checkout Page*/    
        if(count($values['wdm_user_custom_data_value']) > 0)
        {
            $return_string = $product_name . "</a><dl class='variation'>";
            $return_string .= "<table class='wdm_options_table' id='" . $values['product_id'] . "'>";
            $return_string .= "<tr><td>" . $values['wdm_user_custom_data_value'] . "</td></tr>";
            $return_string .= "</table></dl>"; 
            return $return_string;
        }
        else
        {
            return $product_name;
        }
    }
}

Step 5: Add Custom Data as Metadata to the Order Items

One more additional step that needs to be done is to add the custom data as metadata to the order items. This metadata will then be displayed in the orders section of WooCommerce for your reference. It will also be used in the confirmation email that is sent to the user after a payment is made. This metadata can be incorporated into the order using the following code.

add_action('woocommerce_add_order_item_meta','wdm_add_values_to_order_item_meta',1,2);
if(!function_exists('wdm_add_values_to_order_item_meta'))
{
  function wdm_add_values_to_order_item_meta($item_id, $values)
  {
        global $woocommerce,$wpdb;
        $user_custom_values = $values['wdm_user_custom_data_value'];
        if(!empty($user_custom_values))
        {
            wc_add_order_item_meta($item_id,'wdm_user_custom_data',$user_custom_values);  
        }
  }
}

Step 6: Remove User Custom Data, if Product is Removed from Cart

Beware though! Your work does not end here. Let us assume now that instead of proceeding to the payment section the user deletes an item from the cart…then what? You don’t want the custom data lingering around in your WooCommerce session. So to avoid such a scenario we’ll write some code below to remove the custom data from the WooCommerce session.

add_action('woocommerce_remove_cart_item','wdm_remove_user_custom_data_options_from_cart',1,2);
if(!function_exists('wdm_remove_user_custom_data_options_from_cart'))
{
    function wdm_remove_user_custom_data_options_from_cart($cart_item_key, $WC_Cart)
    {
        global $woocommerce;
        // Get cart
        $cart = $woocommerce->cart->get_cart();
        // For each item in cart, if item is upsell of deleted product, delete it
        foreach( $cart as $key => $values)
        {
        if ( $values['wdm_user_custom_data_value'] == $cart_item_key )
            unset( $woocommerce->cart->cart_contents[ $key ] );
        }
    }
}
?>

Best Practices for Adding Custom Data to WooCommerce Orders

Add Custom Data WooCommerce

To keep things running smoothly when adding custom data to WooCommerce orders, here are a few key tips:

    1. Keep It Relevant:Only ask for information that you really need. Too much unnecessary data can confuse customers and clutter up your system.
    2. Use Clear Labels: Make sure WooCommerce custom fields have clear and simple labels. This helps customers know exactly what info you’re asking for and why.
    3. Validate User Input: Implement checks to ensure the data collected is accurate and in the correct format. This helps avoid errors and reduces the need for manual fixes.
    4. Secure Data Handling: Always handle custom data securely. Use proper sanitization and validation techniques to protect against security issues.
    5. Test Thoroughly: Before going live, test your custom data fields to make sure they work correctly across different devices and scenarios.

By following these practices, you’ll make the process smoother for both your customers and your team.

Final Thoughts

Integrating custom data into your WooCommerce store can significantly boost its functionality and the overall customer experience. By following the steps in this guide and keeping best practices in mind, you’ll make order management smoother and more personalized.

If you ever run into any issues or have unique requirements that this guide doesn’t cover, we’re here to help. Our team of WooCommerce experts is ready to provide you with customized solutions and support. Don’t hesitate to get in touch with us for any assistance you need.

 

Note:  This code is compatible only with the versions of WooCommerce prior to 3.0. You can find the code for WooCommerce v3.0 and ahead right here

FAQs

1. Why would I need to add custom data to my WooCommerce store?

Adding custom data personalizes the shopping experience, collects valuable customer info, and improves order management.

2. How can I add custom fields to WooCommerce products?

Use plugins, custom fields on product pages, or add fields to the checkout page to capture additional customer information.

3. Are there any risks associated with adding custom data to WooCommerce?

Yes, there can be conflicts with other plugins, theme compatibility issues, and performance impacts. Follow best practices to minimize these risks.

4. Is there support available for adding custom data to WooCommerce?

Absolutely. Our team of WooCommerce experts can provide customized solutions and support to ensure your store runs smoothly.

Picture of Akshaya Rane

Akshaya Rane

156 Responses

  1. Hi, this is exactly what I am looking! thanks, I do have some questions, I am very new to Woo Commerce and I don’t know where to put all this code, I mean, functions.php? or there is something else for WC?, also the input form can be outside the product page? I am trying to archieve something like:

    Choose your model (not a wc category, just a custom value) > choose your design (wc products) > wc cart

    and in the wc cart get the custom value, also in the payment area, email, etc

    thanks

  2. Hi Victor,

    Glad the post was helpful to you!

    You can add the code in two ways
    1)You can add the code in the functions.php file of your current theme and you will be able to achieve the functionality.
    2)Alternatively you can create a plug-in and add it to the plugins folder which is present in the wp-content folder.
    I would recommend that you use the second method, as, in the first method the code will no longer be available to you if you change your theme or upgrade your theme.

    1. Hello, thanks for answering, I am having problems creating the custom form, first I tried just adding some custom fields to the product as you imagine it didn´t work, then I try just adding a form in a static page (page-slug.php) with the values in the form code part, and it didn´t work, what am I doing wrong? wrong values?

      I am trying to get the user set a value, then choose a product from a woocomerce category, and make the order and I receive the order with his/her value set, also display the value in the payment area (I am using paypal) and in the order email.

      thanks

  3. I’m trying this out, but nothing seems to happen. Is this action still available, or has it changed?

    wp_ajax_wdm_add_user_custom_data_options

    1. Maybe I misunderstood this. Is that not a standard Woocommerce hook? I could really use some help.

      1. Hi Duke,

        This is not standard WooCommerce hook. There is an AJAX request on the Add to Cart button so we have created a custom handler using wp ajax action.

        You will have to create a JavaScript file with the following code

        jQuery(document).ready(function(){
                //code to add validation on "Add to Cart" button
                jQuery('.single_add_to_cart_button').click(function(){
                  //code to add validation, if any 
                  //If all values are proper, then send AJAX request
                  jQuery.ajax({
                            url: ajax_url, //AJAX file path - admin_url('admin-ajax.php')
                            type: "POST",
                            data: {
                                    //action name
                                    action:'wdm_add_user_custom_data_options', 
                                    user_data : wdm_data //send request data
                                  },
                            async : false,
                            success: function(data){ 
                                  //Code, that need to be executed when data arrives after 
                                  // successful AJAX request execution 
                            }
                        });
         })
         });
        

        You will then have to link to this file by enquing it in the php file in which you have written the rest of the code.

        add_action('woocommerce_single_product_summary','wdm_enque_scripts');
        

        In function, “wdm_enque_scripts” enque the script that needs to be executed, when “Add to Cart” button is clicked,

        function  wdm_enque_scripts()
        {
           wp_register_script( 'wdm_singleProductJs', plugins_url('/js/wdm_single_product_page.js', __FILE__), array('jquery'), false, true ); 
            wp_enqueue_script('wdm_singleProductJs'); 
                     
            $array_to_be_sent = array( 'ajax_file_path' => admin_url('admin-ajax.php')); 
                 
            wp_localize_script( 'wdm_singleProductJs', 'wdm_object', $array_to_be_sent);
        }
        

        Make sure the name of the JavaScript file and path of the file is the same as your JavaScript file.

        1. I just wanted to come back and leave my feedback about this. I used it for a modified purpose: to allow a customer to upload a custom logo to attach to the product they were purchasing. Because of this, I needed to make sure the session was unset after it was used.

          So right after this line:
          $option = $_SESSION[‘wdm_user_custom_data’];

          I added:
          unset($_SESSION[‘wdm_user_custom_data’];

          How can I ensure the session is cleared if someone deletes the item from the cart? As it stands right now, if I delete an item from the cart, and then add a different item with no custom logo, the logo from the deleted item becomes attached to the new item?

          1. Hi Duke,

            The code you have used unsets the data from the custom session. However what you need to do for your requirement is to unset the data from the WooCommerce session. In step 6 we are doing just that, i.e we are unsetting the data from the WooCommerce session. However the hook used in this step is to unset the WooCommerce session if all the items are removed from the cart. For your requirement you need to find a hook which unsets the WooCommerce session data if only one item is removed from the cart.

          2. Hi Akshaya,

            Thanks for the wonderful tutorial. I have followed the steps instructed above but i encountered an issue.
            When i cleared all browsing data on my browser and added a new item it seems that the custom data does not get added to the cart item. (I did some checks and it seems that the $_SESSION[‘wdm_user_custom_data’] variable does not get set.
            However, when i add another item the custom data gets added. Would really appreciate your guidance on what i could be doing wrong?

    2. Thanks for this code, it was a life saver.

      I did modify the javascript file and php code a little to support multiple variables. I just turned them into a single string in the php code instead of trying to pass along an array.

  4. Thank you very much for your code.It helped me a lot. I also Used this code to add the custom form data to cart and order as well.It is working fine.
    I have added the form with custom values for specific products, so that the customers can select one of the value from the radio button set.
    The Problem comes when the customers purchase the simple product that do not have any custom field to select. But the values appears to the cart and checkout page for these product too. The values should not come .
    Please help me how can i stop them to come for the others products.

    Thanks

    1. Hi Amit,

      I’m glad the post was helpful!!!

      Regarding your problem, it is not clear from your question if the labels for the custom fields appear in the cart and checkout page or labels along with some values appear in the cart and checkout page.
      If the case is that only the labels are appearing without any custom data then you can use this condition in step 4 where we are displaying user custom data on cart and checkout page
      if(count($values[‘wdm_user_custom_data_value’]) > 0 && !empty($values[‘wdm_user_custom_data_value’]))

  5. Hi Akshaya,
    Label not problem.It is not removing the last custom field value from session even after cart empty or I removed the product from the cart.
    Can you please help so that i can add this check.

    1. Hi Amit,
      The hook used in step 6 is to unset the WooCommerce session if all the items are removed from the cart. For your requirement you need to find a hook which unsets the WooCommerce session data if only one item is removed from the cart.

      1. Hello, I know this post is old but has anyone found a hook which unsets the WooCommerce session data if the original item is removed from the cart? Any help would be greatly appreciated.

        1. Hey Rich, here’s what you are looking for

          remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_product_data_tabs', 10 );
          add_action( 'woocommerce_single_product_summary', 'woocommerce_output_product_data_tabs', 11 );
          

          Even, priority 10 is ok

          1. My custom data is also attached to that product in the cart for which we don’t want to add this detail

          2. I know this post has become very old but still it is useful for many. Thanks Akshaya for the much needed information on handling custom data with woocommerce.

            I have also followed the same steps. but somehow I m not able to unset the sessions. In other terms, the custom values are added to cart for simple products as well which doesn’t have any custom fields. Please help.

  6. $array_to_be_sent = array( ‘ajax_file_path’ =&gt; admin_url(‘admin-ajax.php’));
    Hi this is exactly the code i need, but the issue is that when i try to run the above code an error is generated against the line of code shown above. It tells that “=” shouldnt be there. What to do, please help.

    1. Hi Subarna,
      The code you need to add is
      $array_to_be_sent = array( ‘ajax_file_path’ = admin_url(‘admin-ajax.php’));
      & gt; got added to the code as a result of a typo error. Thanks for pointing it out.

  7. Hi!
    may be i miss something 🙂

    what is $_POST[‘user_data’] ?

    i just need to save an array for each item and retrive it in the order detail.

    thanks a lot

    1. Hi Matt,
      $_POST[‘user_data’] is custom data sent via AJAX, to store in a session. This can be any variable. You can pass you array which contains the custom data using this code. I hope that answers your question 🙂

      1. Hi Akshaya,
        thanks a lot to reply me.
        Just to try, without add any custom field to the product, I modified wdm_enque_scripts callback like this:

        add_action('woocommerce_single_product_summary', 'wdm_enque_scripts');
        function wdm_enque_scripts() {
           wp_register_script( "wdm_singleProductJs", get_template_directory_uri() . '/_assets/js/wdm_single_product_page.js', array('jquery') );
           wp_localize_script( 'wdm_singleProductJs', 'myAjax', array( 'ajaxurl' =&gt; admin_url( 'admin-ajax.php' ), 'user_data' =&gt; array('website' =&gt; 'www.google.com', 'Name:' =&gt; 'Matteo')));        
           wp_enqueue_script( 'wdm_singleProductJs' );
        }
        

        I saw that u pass just the ajaxurl, and not the “user_data”.

        And the javascript jQuery click event like this:

        jQuery(document).ready(function(){
                //code to add validation on "Add to Cart" button
                jQuery('.single_add_to_cart_button').click(function(){
                  //code to add validation, if any 
                  //If all values are proper, then send AJAX request
                  jQuery.ajax({
                            url: myAjax.ajaxurl, //AJAX file path - admin_url('admin-ajax.php')
                            type: "POST",
                            data: {
                                    //action name
                                    action:'wdm_add_user_custom_data_options', 
                                    user_data : user_data //send request data
                                  },
                            async : false,
                            success: function(data){ 
                                  //Code, that need to be executed when data arrives after 
                                  // successful AJAX request execution 
                                  console.log('success')
                            }
                        });
         })
         }); 
        

        But my console log say that user_data is undefined.
        What im wrong?
        Thanks again

        Matteo

        1. ok! I did it 🙂
          this is the right code:

          <?php
          add_action('woocommerce_single_product_summary','wdm_enque_scripts');
          function wdm_enque_scripts() {
             wp_register_script( "wdm_singleProductJs", get_template_directory_uri() . '/_assets/js/wdm_single_product_page.js', array('jquery') );
             wp_localize_script( 'wdm_singleProductJs', 'myAjax', array( 'ajaxurl' =&gt; admin_url( 'admin-ajax.php' ), 'user_data' =&gt; array('website' =&gt; 'www.google.com', 'Name:' =&gt; 'Matteo')));        
             wp_enqueue_script( 'wdm_singleProductJs' );
          }
          [/code]
          
          [code]
          jQuery(document).ready(function () {
              //code to add validation on "Add to Cart" button
              jQuery('.single_add_to_cart_button').click(function () {
                  //code to add validation, if any 
                  //If all values are proper, then send AJAX request
                  jQuery.ajax({
                      url: myAjax.ajaxurl, //AJAX file path - admin_url('admin-ajax.php')
                      type: "POST",
                      data: {
                          //action name
                          action: 'wdm_add_user_custom_data_options',
                          user_data: myAjax.user_data //send request data
                      },
                      async: false,
                      success: function (data) {
                          //Code, that need to be executed when data arrives after 
                          // successful AJAX request execution 
                          console.log('success' + myAjax.user_data)
                      }
                  });
              })
          }); 
          

          Now, it’s possible to grab this custom data and show it in the order detail in the backend? thanks again a lot 🙂

  8. Hi Akshaya Rane, Nice article helped us.
    I think wdm_remove_user_custom_data_options_from_cart is not required, Please confirm ?

    1, Is this condition correct? Custom value matching with cart key?
    $values[‘wdm_user_custom_data_value’] == $cart_item_key
    2,set_quantity method in class-wc-cart.php is unseting the value. (unset( $this->cart_contents[ $cart_item_key ] );)

    Thanks and Regards
    ThemeHigh

    1. Hi,
      I’m glad that the article was helpful!!
      Regarding your questions.
      1. The function wdm_remove_user_custom_data_options is required. This is because the code in class-wc-cart.php is unsetting the the WooCommerce cart default data. However, it does not unset the custom data. To be able to achieve that the function wdm_remove_user_custom_data_options is required.

      2. The condition , $values[‘wdm_user_custom_data_value’] == $cart_item_key works fine when all the products are removed/deleted from the cart.

      I hope I have answered your question!

    2. Hey, i was wondering, is this supposed to work even with a product that has some default variations enabled? Like a sign shop – They have standart variations for size and material but the text on the sign should be custom and sent by input, i wasen’t able to achieve this using your tutorial.

      Also it is not clear if the javascript file, which was not mentioned on the post but in the comment is obligatory, is it? If yes, should i enque the script before step 1 or after step 6? Can you explain this file a little more?

      Thx in advance

      1. Carlos, in reply to your first question, yes the code will work for variable products. About the JavaScript file, it is mandatory and should be enqueued before step 1.

        Hope that answers your questions 🙂

  9. Hello, and thank you so much for this snippet!
    I am trying to set more meta to a cart item with this method, but it is not easy (or I use a wrong approach). So I send my meta fields one-by-one via AJAX ( 3 fields, 3 ajax post). That is okay, they get into the session. In the functions.php I make an array (manually) with the posted field names, and try to use a foreach in every step to go through them but it is does not work – just on the first element of the array. Without foreach (assigning a function to each meta) it works, but the redundancy is huge :/ Any suggestions?

    1. Yaay! Solution:
      Step 2: I’ve collected the new values into an associative array ($new_value with more members) with foreach and returned the merge outside the loop.
      Step 3: Just simply put the return item outside the loop.
      Step 4: if isset(member), add the line to return string.
      Other steps work with foreach inside, no magic.

  10. I just need this, but i cant make it work, im trying other approach because i dont have any custom field, i just want to add just some custom data.

    global $woocommerce;
    $woocommerce->cart->empty_cart(true);

    foreach($ordenes as $orden){
    $product_id = $orden[‘id’];
    $qty = $orden[‘qty’];
    $found = false;

    $woocommerce->cart->add_to_cart( $product_id, $qty );
    }
    echo do_shortcode(‘[woocommerce_cart]’);
    die();

    As you see i dont use the product page, instead i have my own script to add items to the cart. I tried to use your functions but nothing happend, any ideas?

    1. Hi Clark,

      I need a few clarifications from you
      1. Are you trying to add products to the cart with your own script or are you trying to add custom data to the cart with your own script.
      2. What is the value that is being saved in the variable $ordenes

      1. Thanks for your answer!, that script is for add products to the cart, and it works. Now i want to add custom data, but i tried a lot of examples and they dont work, maybe because i using my own script to send items to the cart.

        The script I posted before, was a simplied version of mine, but has the essentials. The $ordenes array contains a list of products (id, quantity) that i send from a form via ajax.

        Thanks in advance!

        1. Hi Clark,
          My understanding of your question is that you have written a custom script to add products to cart. You now want to add custom data to the products in the cart. In order to achieve this you will have to add the custom data to a WooCommerce session as shown in Step 2. You will have to append this code to the add to cart event in your script.
          Hope that helps!

  11. I am very new to Woo Commerce and I don’t know where to put all this code,so please give me all code in one place

    1. Hi, Ramesh,

      All the above code should be added to the functions.php file of your theme. Alternatively, you can create a separate plugin folder and add this code to a php file in this folder.
      My suggestion to you would be to use the second approach as any customizations done in the theme files will be lost in case the theme is updated.

    1. Hi Polyt,

      Yes, you can see the order items on the order page.
      The admin can see the order items and order details in the admin dashboard in the Order menu under the WooCommerce tab.
      The end user can see the order details on the My Account page when he is logged in.

      1. Hi Akshaya

        Is it possible to place the values on an order an the order-details.php page as a successful order has been made ?

        like so :

        <?php
        add_action('woocommerce_add_order_item_meta','wdm_add_values_to_order_item_meta',1,2);
        if(!function_exists('wdm_add_values_to_order_item_meta'))
        {
          function wdm_add_values_to_order_item_meta($item_id, $values)
          {
                global $woocommerce,$wpdb;
        
                $user_custom_values = $values['width'];
                if(!empty($user_custom_values))
                {
                    wc_add_order_item_meta($item_id,'wdm_user_custom_data',$user_custom_values);  
                }
          }
        }
        
  12. Hello Akshaya R

    Thanks For this Article, as in this tutorial you add custom data to the cart, checkout and order meta , same i want to add product category in cart, checkout page and order meta. it will be a huge help if you give me solution for this . waiting for your positive response , Thanks in advance 🙂

    1. Hi Priyank,

      You will not need to add product category to session to display in check out page, cart page and order meta.
      In order to display product category in cart and checkout page you will have to fetch the product category based on the product_name. This will have to be done in step 4.
      To add product category to order meta you will have to fetch the product category based on the $Product_id. This will have to be done in step 5 using the WooCommerce_add_order_item_meta.
      I hope that answers your question!

  13. Hi,

    Thanks for the great tutorial, somehow I came up with different but just wanted to know if there’s also available hook for updating custom value? what I mean is in the Update Cart I also want the ability for custom value to update depending on the changes users made.

    I tried woocommerce_update_order_item_meta hook and no use, though WooCommerce has wc_update_order_item_meta, which I believe there’s also corresponding hook for that I just don’t know what or when it’s located.

    Can you help me find it out?

    Thanks,
    Ryan S

  14. Hi,
    thanks very much for this post, Here is my question:
    In my website, i have more than 3,00,000 products that changes every day, so I think it is not wise move to store in wp_posts and wp_postmeta, so I stored all these products in another table like “diamond_details”, so how can I add products from this table into my cart?

    I think it is something like same as above, but not getting exact idea how to do this, which code to be added and where to put that code, can you please help me?

    1. Hi, Ketan,

      Based on the details that you have supplied me with I understand that you have saved all data from wp_posts and wp_postmeta in the diamond_details and what you require is to add products from this table into the cart.

      The above post essentially deals with adding custom data, which has been added by the user at the front end. So your requirement will not be met by the the above post.
      Your requirement will need some changes in the core WooCommerce code which will fetch the products from this table. However such a change would not be advisable as these changes would be lost when you upgrade the plugin.

      Another option would be to save only the wp_postmeta data in the diamond_details table while keeping the wp_posts data as it is. This data can then be fetched based on the product id in Step 2 and then the process will remain the same as explained in the post.

      Hope this helps!

  15. Thanks very much Akshaya for reply.
    Here my problem is that i have already more than 2,00,000 rows in wp_postmeta and all 3,00,000 diamonds are updating daily. so I must keep in separate table and to save those data in wp_postmeta would be very difficult.

    moreover, I will never make any update in plugin or theme or anywhere else, so it’s not the problem for me if I do any changes in core Woocommerce files, so can you please suggest me how to make changes in core woocommerce file and what code need to be added and where? it will be huge help for me if you solve this problem. Thanks very much in advance…

    1. Hi Ketan,

      Your requirement is beyond the scope of this post and would require extensive effort for implementation. In case you would like to take this forward please contact us at [email protected] and we shall provide it to you as a service.

  16. Hi,

    Thanks so much for this post – it is quite literally exactly what I’ve been searching for. Sadly I’m a complete novice when it comes to PHP and WordPress so I’m struggling a bit…a lot! to get this working. So far I have…

    1. Added all six parts from your initial post to my /wp-content/themes/THEMENAME/functions.php

    2. Created a js file as detailed later in your post. My js file lives in /wp-content/themes/THEMENAME/js/

    I’m a little confused what the name of my JS file should be? So I went with “wdm_single_product_page.js”

    3. I’ve added additional function to functions.php in same location as step one. Sadly I get the following error:

    Parse error: syntax error, unexpected ‘=’, expecting ‘)’ in …. functions.php

    Reading on I noticed another user had this issue and they resolved it by removing > – I don’t have this listed but still get the error – see below:

    $array_to_be_sent = array( ‘ajax_file_path’ = admin_url(‘admin-ajax.php’));

    Any help / guidance you can provide would be very much appreciated. Is the JS file I’ve created correct? Is the array_to_be_sent variable being set correctly?

    Thanks in advance
    Paul

    1. Hi Paul,

      The below line,
      $array_to_be_sent = array( ‘ajax_file_path’ = admin_url(‘admin-ajax.php’));
      should be written as follows,
      $array_to_be_sent = array( ‘ajax_file_path’ => admin_url(‘admin-ajax.php’));

      This should be sufficient to resolve the error that you are getting.

  17. Hi Akshaya,

    I require your help in sorting out my issue. I want to add a field for extra fees (additional cost) on checkout page, If user select the field then only the fees should be applicable on the total order amount else not.

    Could you please advise how I can achieve this.

  18. Hi, after few weeks i find your post, and its GREAT! I’m fighting with my input fields, is it possible to set price from added input to my value? i added 2 custom fields to my category,but i can’t validate price, and save values from fields

  19. Hi, sorry to bother you again,but i add your 6 steps code to my theme/function .php file, i crate js file, change url to my path, change = to => in “$array_to_be_sent = array( ‘ajax_file_path’ => admin_url(‘admin-ajax.php’));”
    Then i added my input field using ‘woocommerce_single_product_summary’ and it still doesen’t save my values from inputs, i don’t know what is wrong with my code ;((

  20. hi Akshaya, very nice tutorial and thanks for sharing. i am using the easy reservations free version which does not integrate into woocommerce. i want to be able to add the reservation details into the shopping cart and then checkout from there. can you enlighten me how to achieve that with this tutorial? like treat the reservation fields as custom data and just add the cart button to it? i really need this.
    Thank you so much.

    1. Hi Abraham,
      Sorry for delayed reply. I somehow missed your comment.
      Regarding your question, you need to add a link between custom reservation & a single product. You will also need to add code to load the corresponding custom reservation field on the single product page dynamically.

  21. Hi All,
    Am adding order item meta like below.
    $custom_img_thumb=”;
    wc_add_order_item_meta($item_id,’custom_img_thumb’,$custom_img_thumb);
    This is adding to database table properly but, the image source is data url. In the file `class-wc-order-item-meta.php` this function `wp_kses_post()` is removing `data:` word from image data url.So it’s not fetching properly.can anyone help me out.

    1. Hi Krishna,

      Save the Image Id instead of the Image URL. The image source can be retrieved using the image Id.

  22. Hi. Thanks for this post.

    I’m new in WooCommerce and I want add to cart a custom item, with custom values from a form.
    If I have my form, where to I need point the target of my form?
    I just want add a simple item in the cart with custom values, including the price.

    Thanks.

    1. Hi Jesus,

      Instead of adding a custom form on the single product page you should add custom fields and save it to the WooCommerce session when product is added to the cart.

      You should be able to achieve your requirement if you follow the above post.

    1. Hi Prasanth,

      You can add the form on any of the woocommerce actions for a single product page. For example, ‘woocommerce_single_product_summary’.

      The form position will depend on the action you select and its priority. For more actions, refer the single product template file.

  23. Hi Akshaya,

    Thanks for all the work.
    I got through all the steps, but I can’t get it to work.
    I want to sent the data when I’m at the shoppage, when I click add to cart. So not on the Single product page. On both pages I can’t get it to work.

    Thanks in advance.

    1. Alex, the code that I have given in this post is for single product page. In order to display the data on the shop page too you will have to write some additional functionality. To give you a gist here’s what you will have to do. On the ‘Add to Cart’ button event on the shop page you can trigger a dialogue box which will have the custom fields. Users can then add their preferences here after which the product will be added to the cart. In this way you can display the custom fields on both pages.

  24. Thanks a million for your help, can i do anything to make this work on mobile phones?
    please do reply

    1. Hey Huzaifa, the solution given above is based exclusively on functionality. It will not affect how the cart is rendered to the front-end. In order for it to work properly on mobile phones the theme you are using should be responsive.

  25. Thanks for this script, however I have a problem. When using Firefox or Safari, when I am taken to the cart page, the custom data fields are missing. Doing the exact same thing in Chrome works and the fields are listed correctly. There are no JS errors. Can you think what could be causing this? Thanks.

  26. Hi Akshaya Rane ,

    how to create this fields (Name ,slogan ,website etc..) in single product page ? Please explain me.

    1. Hi Anand,

      You will have to add additional fields on the ‘woocommerce_single_product_summary’ hook. To add custom fields, you will have to use HTML fields as per your requirement. For example:

      <label>Name</label> 
      <input type="Name" placeholder="Enter Your Name" name="user_name">
      

      Does this answer your question?

  27. Hi Akshaya Rane,

    I’ve followed all your steps to store custom data into sessions. When I click on “Add to cart” button, an ajax call is sent and getting a success message after the data is stored in session, but after that it hasn’t redirected to cart page. Can you please help me out.


    Thanks

    1. Hi Sandeep,
      There is setting in WooCommerce to redirect to the cart page after adding a product to the cart. To achieve this you will gave to go to WooCommerce Settings –> Products –> Display –> “Add to cart behaviour” Here you will need to save “Redirect to the cart page after successful addition” setting. Hope that helps!

  28. Hello, I am working on a website but I am a complete novice, I am using a plugin woo detail page builder and another plugin woo custom product options, I have created a form using the two plugins, I need to know if this code will help me and how

    1. Emmanuel, yes you can use the above code.
      Just to make things simpler though you can use WooCommerce Extra Product Options plugin (http://codecanyon.net/item/woocommerce-extra-product-options/7908619) to create form for single product and change Product price accordingly. This allows to save details in the Cart as per the demo of the plugin, but just make sure it saves details in Order meta

      P.S. If you decide to use the plugin it would be best if you ask the developers if the plugin is suitable for your requirement.

  29. Hi,

    I have followed the instructions as per this post. The main issue i faced was that it doesn’t work for the first item which i added to the cart, subsequent items added do work though.

    Appreciate your assistance please

    1. Hey Joshua, the code provided above is complete and should work if implemented as is. I’ve never come across the issue that you have mentioned.

      Could you please go through the steps again to verify if you’re missing something?

  30. Hi,
    I’m new to Woocommerce. I’ve added the codes to the function.php file of my theme. Now how do I add the custom form itself?

    Thanks

    1. As mentioned above you can use the ‘woocommerce_single_product_summary’ to create this field and show it before adding the code shown here at this post.

      function wooc_add_input_field() {
      ?>

      *

      <?php
      }
      /******** ADICIONA O CAMPO, O NUMERO AO FINAL DEFINE A ORDEM DO HOOK ***/
      add_action( 'woocommerce_single_product_summary', 'wooc_add_input_field', 25);

      Hey Akshaya, this is a great post, wish i had half of your knowledge! Do you mind if i translate this post to Brazillian portuguese in my non-profitable, personal blog (with the credits, of course)?

      1. Bruno, thanks for helping out Jun Dolor with his query. Also, I’m glad you found the post helpful.
        Please feel free to go ahead and use the solution with appropriate credits.

  31. Dear Akshaya,

    Thank you for this tutorial, it has helped me a lot so far! I do have a small problem with this approach and I can’t get fixed yet. When I add a custom product to the cart, everything works just fine. When I proceed to add another product to the cart (the same product with different custom field data), it doesn’t add a new product to the cart. Instead, it adds one to the quantity of the original ordered item.

    In your scenario, this means if I would like two video template designs – one with the name “You” and another one with the name “Me” – in the cart there is only the video template design with the name “You” with a quantity of 2.

    My gut feeling tells me it has something to do with the cart_item_key which gets reused for every order of that product, disregarding the custom item data. Do you have an idea how to solve this problem? Am I missing something?

    1. Kevish, If you are adding custom data to cart, it should add each product into cart separately. There seems to be some problem with the addition of data to the WooCommerce session. To trouble shoot you will have to check the session data that gets added at “Step 2”.

  32. jQuery(document).ready(function(){
    //code to add validation on “Add to Cart” button
    jQuery(‘.single_add_to_cart_button’).click(function(){
    //code to add validation, if any
    //If all values are proper, then send AJAX request
    alert(‘sending ajax request’);
    var user_data = ‘user_data’;
    var id = ‘id’;

    var ajaxurl = ”;
    jQuery.ajax({
    url: ajaxurl, //AJAX file path – admin_url(‘admin-ajax.php’)
    type: “POST”,
    data: {
    //action name
    action:’wdm_add_user_custom_data_options’,
    user_data : user_data,
    id : id

    },
    async : false,
    success: function(data){
    //Code, that need to be executed when data arrives after
    // successful AJAX request execution
    alert(‘ajax response recieved’);
    }
    });
    })
    });

  33. Thank you very much for your awesome tutorial. Very helpful and educational. Just one question regarding step 5 “Add Custom Data as Metadata to the Order Items” I found that sending an array to wc_add_order_item_meta() of course serializes the meta value on the table woocommerce_order_itemmeta. I’m storing several values in $values[‘wdm_user_custom_data_value’]

    The problem is WC is unable to display that order item meta in the admin area / emails. I mean WC cannot show serialized data as item meta. I tried adding a simple text variable and it worked, but storing an array like isn’t. Any suggestion? Many thanks.

  34. Hi, it’s great you’ve given this solution to us all, thank you.

    Would the process be similar to add custom data to the whole order?

    I’m attempting to add custom meta data to the order from a page after cart but before checkout.

    Any guidance would be greatly appreciated.

  35. Hi, and thanks for writing the guide 🙂

    I need to add the product programatically, preferably through wp_ajax. I’ve tried your snippets for hours now but I can’t get it to work.
    Adding the product is no problem. It’s the custom data and that the product need to be added individually in the cart thats the problem.

    Any help is appreciated 🙂

  36. First of all thx for this great post! I manage to follow up pretty fast for this one, however I have a slightly different situation here.

    In my product there is a set of predefined sizes as well as a custom size text field. How do I get to switch the cart data to display information between my predefined size & custom data? I added a “custom size” into my dropdown, & when user selects it, the text field would show up.
    Would really appreciate if you could guide me out on this. Thanks!

  37. Hello, Akshaya R

    I want to make relation between Gravity form and woocommerce on my site , So when user submit form its unique entry_id store in session such that it will store in post meta(meta_value) of that Order and later i will able to display that entry_Id in fornt of each order_id in woocommerce my account page , for now i am able to fetch entry_id for each user . So how i can use this code to accomplish that..?

  38. Hii I tried this code on my wordpress site. But having little problem.
    Here is what I did is, I added the custom field on shop page in product loop.
    Now the problem is it’s not working

    here is my code:

    /**
    * The following hook will add a input field right before “add to cart button”
    * will be used for getting Name on t-shirt
    */

    function add_name_on_product_loop() {
    echo ‘

    Spicy Level

    level 1
    level 2
    level 3

    ‘;
    }
    add_action( ‘woocommerce_after_shop_loop_item’, ‘add_name_on_product_loop’, 9 );

    function add_name_on_tshirt_field( $cart_item_data, $product_id ) {
    if( isset( $_REQUEST[‘spicy_level’] ) ) {
    $cart_item_data[ ‘spicy_level’ ] = $_REQUEST[‘spicy_level’];
    /* below statement make sure every add to cart action as unique line item */
    $cart_item_data[‘unique_key’] = md5( microtime().rand() );
    }
    return $cart_item_data;
    }
    add_action( ‘woocommerce_before_add_to_cart_button’, ‘add_name_on_tshirt_field’ );

    function tshirt_name_validation() {
    if ( empty( $_REQUEST[‘spicy_level’] ) ) {
    wc_add_notice( __( ‘Please enter a Name for Printing…’, ‘woocommerce’ ), ‘error’ );
    return false;
    }
    return true;
    }
    add_action( ‘woocommerce_add_to_cart_validation’, ‘tshirt_name_validation’, 10, 3 );

    function save_name_on_tshirt_field( $cart_item_data, $product_id ) {
    if( isset( $_REQUEST[‘spicy_level’] ) ) {
    $cart_item_data[ ‘spicy_level’ ] = $_REQUEST[‘spicy_level’];
    /* below statement make sure every add to cart action as unique line item */
    $cart_item_data[‘unique_key’] = md5( microtime().rand() );
    }
    return $cart_item_data;
    }
    add_action( ‘woocommerce_add_cart_item_data’, ‘save_name_on_tshirt_field’, 10, 2 );

    function render_meta_on_cart_and_checkout( $cart_data, $cart_item = null ) {
    $custom_items = array();
    /* Woo 2.4.2 updates */
    if( !empty( $cart_data ) ) {
    $custom_items = $cart_data;
    }
    if( isset( $cart_item[‘spicy_level’] ) ) {
    $custom_items[] = array( “name” => ‘Name On spicy_level’, “value” => $cart_item[‘spicy_level’] );
    }
    return $custom_items;
    }
    add_filter( ‘woocommerce_get_item_data’, ‘render_meta_on_cart_and_checkout’, 10, 2 );

    function tshirt_order_meta_handler( $item_id, $values, $cart_item_key ) {
    if( isset( $values[‘spicy_level’] ) ) {
    wc_add_order_item_meta( $item_id, “spicy_level”, $values[‘spicy_level’] );
    }
    }
    add_action( ‘woocommerce_add_order_item_meta’, ‘tshirt_order_meta_handler’, 1, 3 );

  39. I’m having trouble including this in a plugin I’m working on. If you look at the code below you can see it has more or less the same structure of your article. The reason I’m currently verifying isset($_SESSION) after step 1 is because currently if I don’t, the data that Step 2 will get from the Session is the PREVIOUS custom data.

    I.e. considering a text field for custom data, if I enter HELLO and press add do cart, it will add the product but without any custom data at first. If I open the product again, insert some other string and press add to cart, it will be added along with the custom data from the previous entry (i.e. “HELLO”). After this it is always adding the previous cart’s custom data. Using the conditional on isset($_SESSION) makes that code not to run.

    I’ve checked that both $_POST and $_SESSION variables are correctly populated after the ajax callback, but it’s like the WooCommerce add to cart functions are being called before the ajax callback – I’ve tried messing with the priorities but it didn’t help.

    Any ideas on how to trouble shoot this?

    function __construct() {

    // WC Step 1 – Add data to a custom Session – AJAX callback
    function ajax_custom_data_callback_inline () {
    session_start();
    print_r ($_POST);
    $_SESSION[‘custom_meta_data’] = $_POST[‘my_data’];
    //print_r ($_SESSION);

    wp_die();
    }

    // AJAX hooks
    add_action(‘wp_ajax_’ . ‘custom_data’, ‘ajax_custom_data_callback_inline’, 1);
    add_action(‘wp_ajax_nopriv_’ . ‘custom_data’, ‘ajax_custom_data_callback_inline’, 1);
    // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    if ( isset( $_SESSION['custom_meta_data'] ) ) {

    // Step 2 – Add data to WooCommerce session
    add_filter( 'woocommerce_add_cart_item_data', 'my_add_cart_item_data', 10, 2 );

    // Step 3 – Get data from WC session and place it in the Cart object
    add_filter( 'woocommerce_get_cart_item_from_session', my_get_cart_items_from_session', 10, 3 );

    // Step 4 – Add custom details to Order array
    add_filter( 'woocommerce_get_item_data', 'my_get_item_data', 10, 2 );

    // Step 5 – Add custom Details to Order Meta Data
    add_action('woocommerce_add_order_item_meta', my_'add_values_to_order_item_meta',10,2 );

    // Step 6 – Remove custom Data if Product is removed from cart
    add_action('woocommerce_before_cart_item_quantity_zero', 'my_remove_user_custom_data',10,1 );

    }
    // rest of the plugin's code
    }

    1. I think I got it sorted by using only one single call for start_session right after the plugin initiates, instead of the two calls.

  40. I have problem when “Order Again” from account panel(view order) does not include custom data woo commerce order on product. How i can solved this.

  41. Wow this is one of the most explained code I have come across. Quick Question. I dont use the product or shop pages instead i created a form. For example customer wants a curtain then selects a fabric type with radio button the with and length and so forth. Will this snippet still work?

  42. Should this work for guest too? For some reason on a user’s first checkout, the data is not saved but on the second go round it is

  43. The issue with the first add to cart operation is with ajax. Apparently there’s not a WC session initiated outside any non WooCommerce page and that’s how you get this issue. In my case I solved it by not using ajax calls at all, which suited me fine enough. I might write this down on my blog one of these days.

  44. custom data work fine on Cart & checkout Page but custom data is not shown in final order placed or email confirmation. what to do?

    thanks in advance

  45. Hi thanks for this tutorial. I have a very specific question.
    I am using WordPress lastest version with Woocommerce latest version.

    I have created a shipping zone Flat Fee and COD.

    What I want is that When a user pays through COD, I want only COD as checkout option and when he selects BACS or online payment a flat fee for shipping must be shown.

    For some reason this feature is not working in my site at alrahmanpnp[dot]com

    User is using COD as shipping and he is able to select flat fee which I do not want because I am charging 60/- extra for COD.

    How to write a filter or hook? I am new to WordPress thing

    Regards
    Shahid

  46. This is exactly what I need, the only thing I mis is in step 6 to have the values available again to be able to update some transaction information

  47. Hello, thank you for this precious post… I have followed your all steps for array of data and found good result… i have stored the data inside order_item_meta database but i didn’t get the item in order table inside woocommerce… please guide me how to display that customs meta data array in order table inside woocommerce.

  48. How I did it creating a plugin.. because when I send my data to functions.php by jquery ajax it does not work.
    Here is my code .If there any wrong please help.

    $(document).ready(function(){

    $(“.btn”).click(function(){
    var url= $(‘input#url’).val();

    var text1=$(‘select[name=something]’).val();
    var text2=$(“input[name=’optradio’]:checked”).val();
    $.ajax({
    type:’POST’,
    url: url,
    data:{
    text1:text1,
    text2:text2,
    }
    });
    });
    });

  49. Hi,
    I am developing a plugin for product customization, and there i following your code but the problem have faced is session data. Once i send custom data through ajax on add to cart button click the data is stored, but in cart it did not showed first time but showed second item. Pls help me to solve this.

    Thank you.

  50. Hello Akshaya,
    Your article is fantastic, but there is a question.
    With your code it is possible to change the price of the product before inserting in the cart?
    How can I insert a modified price into the cart?
    Thank you so much

    1. Hey,

      Changing the Product price is out of current article’s scope. However, you can use ‘woocommerce_get_price’ filter to change the price of the WooCommerce product as per your desired conditions.

      Hope this helps!

  51. I’d love to see an update of this using the new CRUD methods. Going to be a lot of hair pulling. I myself am almost bald since they rolled it out.

  52. Hi. I HV an fields like desc,price,ordetprice ,qty and total. My requirement was orderprice need to editable and based on order price total need to be calculated. Need your help.

  53. Hi Akshaya
    Brilliant tutorial and very thoroughly explained. I have used it and its working but I’m encountering a small problem. In the first go the data from the input field went smoothly through all the phases but when I try to do it the second time, the data won’t pass like the first time, it won’t show up on the checkout and order details.
    Please let me know what I’m doing wrong. Thank you

  54. Hello!

    Is function working for now? I’m try to implement it but without success.

    Session create and store the values but filter woocommerce_add_cart_item_data don’t to do anything. It
    it even don’t make unset for session variables

  55. Current code is not working on my end. How i can show my custom product fields in single product page?

  56. hi there Akshaya, it seems like an amazing feature to woocommerce, but somehow i cant get that to work.

    I added before the add-to-cart-button the following field that need to be placed into the order:

    <input type="hidden" id="user_data" name="user_data" value="” />

    also used this JS:

    jQuery(document).ready(function(){
    jQuery(‘.single_add_to_cart_button’).click(function(){
    alert(‘sending ajax request’);
    var user_data = ‘user_data’;
    var id = ‘id’;

    var ajaxurl = ”;
    jQuery.ajax({
    url: ajaxurl,
    type:”POST”,
    data: {
    action:’wdm_add_user_custom_data_options’,
    user_data : user_data,
    id : id

    },
    async : false,
    success: function(data){
    alert(‘ajax response recieved’);
    }
    });
    })
    });

    and the function wdm_add_user_custom_data_options_callback() is getting this value from the post -> $user_custom_data_values = $_POST[‘user_data’];

    but the result im getting in the cart is :

    user_data : user_data

    i haven’t changed anything in your code, placed the functions in my theme functions.php and the JS in my wp-content/themes/main/woocommerce/single-product/add-to-cart/simple.php file, since its a simple product

    also, woocommerce version is = 2.6.11
    and on the inspector in forefox im getting “Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience.” something that souldnt be an error, since you stated in your jQuery.ajax -> async : false,

    any suggestions where to look ?? i really would love to have this working.

    Thank you again

    Jan

  57. Can you please add a link to the article where you describe how to fix 2.6 code like this after updating to 3.0? Thanks.

  58. Hi

    Above code is not working for me …i checked wp_postmeta table for “wdm_user_custom_data” key and i am not getting any value associates with same key.

    Actually i want to store referral id for referral system.

    Can you tell problem related to same?

  59. Hello Akshaya R,

    Thanks for providing everything in detail but I am looking for some similar solution

    How to Supply Console Logs Data into the WooCommerce Cart?

    I am using the third party gadget where they are providing live availability, cost and book now button. When customer click on book now button, it’s redirecting to their website which I want to ignore.

    After doing some google research, I am able to get correct Title & cost under console logs when some is clicking on the book now button.

    $w.event.subscribe(“item.book.click”, function(item) {
    console.log(item);
    console.log(“Title ” + item[3].Name + ” (Date ” + item[4].date + “, Period ” + item[4].period + “, Adults ” + item[4].adults + “, Children ” + item[4].children + “, Infants ” + item[4].infants + “)”);
    console.log(“Price ” + item[3].Availability.Cost);
    });

    All the products are published as a WooCommerce simple product

    Can you please help me how I can supply console logs data such as Title & Price into WooCommerce cart? I want to make third party book now button as a Add to Cart button so it’ll take title & price only.

    If you have any question please let me know.

    Waiting for your favorable reply,

    Thanks,
    Group of Oceninfo

  60. I want to run 2 ajax with different values. So How i can setup session for 2 different names?? so then i can sort different products values on cart page??
    Right now its mixed 🙁

  61. Hi,
    Your article is awesome.

    I am using woocommerce 3.2.5 and I put your code in functions.php. and If I var_dumped the user posted data means it shows nothing. Please help me.

  62. Hi,
    Do you have tutorial how to add cost per product? so, we can get the profit data report per ordered.
    Thanks

  63. Hi,

    This code works perfectly. I’ve been using it for a while now to add custom data to products that are added to cart via a tool that I’ve build on our website.

    Now we’ve decided to also offer products via the standard productpages with a standard add to cart button, which do not need the custom data. If a custom product is added to cart and after that a standard product is added to cart, the standard product will be assigned the custom data from the previously added custom product.

    Can you help to clear the sort of ‘global’ custom data from the cart once it is added to a cart item?

    Thanks!

  64. how to update line item meta according to product quantity change, on clicking update cart button.

  65. Hi Akshaya

    We have used this source code to develop a tracking plugin for our internal purpose. Now we have updated the wooCommerce version 2.9 to 3.6.2. After the update, we have faced a lot of issues. So we have planned to use your source code written for WooCommerce version above 3.0 (https://wisdmlabs.com/blog/add-custom-data-woocommerce-order-2/) and we have faced an issue with “woocommerce_before_add_to_cart_button” hook. This hook not working for me. Please let us know how can I resolve this. Thanks in advance.

  66. Any way of using this to “Add to Cart” from a custom post using javascript and then sending a lot of extra data (generated previously in the script)?

Leave a Reply

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

Get The Latest Updates

Subscribe to our Newsletter

A key to unlock the world of open-source. We promise not to spam your inbox.

Suggested Reads

Join our 55,000+ Subscribers

    The Wisdm Digest delivers all the latest news, and resources from the world of open-source businesses to your inbox.

    Suggested Reads