Adding Custom data to WooCommerce Order during ‘Add to cart’
I was working on an E-Commerce application using WooCommerce WordPress plugin. Here the requirement was users can add custom information for each product they ‘add to cart’. The task seemed difficult at the beginning but after understanding the various hooks it was just a series of steps that needed to be followed and it worked like a charm.
In this post, you will find a step-by-step detailed explanation which will definitely help you to achieve the objective of adding custom information for products during ordering.
Practical use cases:
- Users can provide their own slogans/Quotations/Logos to be printed in T-Shirt / other accessories they purchase.
- Users can choose a product and configure it according to their needs, like for example Car – they can select a car, and configure the engine, tire types, etc and based on it the products price will change.
Steps to add custom data for a product during ‘add to cart’:
1. Add the custom data in session on click of ‘Add to cart’:
On Click of ‘Add To Cart’ button make an ajax call to store the custom entered data in session
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<?php add_action('wp_ajax_twf_add_users_custom_data_options_for_products', 'twf_add_users_custom_data_options_for_products'); add_action('wp_ajax_nopriv_twf_add_users_custom_data_options_for_products', 'twf_add_users_custom_data_options_for_products'); function twf_add_users_custom_data_options_for_products() { $product_id = $_POST['id']; //Product ID $user_custom_data_values = $_POST['user_data']; //This is User custom value sent via AJAX session_start(); $_SESSION['twf_user_custom_datas'] = $user_custom_data_values; //Add product to WooCommerce cart. $product_id = $_GET['product_id']; $quantity = 1; //Or it can be some userinputted quantity if( WC()->cart->add_to_cart( $product_id, $quantity )) { global $woocommerce; $cart_url = $woocommerce->cart->get_cart_url(); $output = array('success' => 1, 'msg' =>'Added the product to your cart', 'cart_url' => $cart_url ); } else { $output = array('success' => 0, 'msg' => 'Something went wrong, please try again'); } wp_die(json_encode($output)); } ?> |
2. Add the Custom Data from Custom Session to WooCommerce Session:
In Step 1 we added the custom data to our created session on click of ‘Add To Cart’ button. After clicking on add to cart the products gets added to cart and WooCommerce session gets created for it. In this step, we will add our custom data to WooCommerce data for this “particular product”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
add_filter('woocommerce_add_cart_item_data','twf_add_custom_data_to_woocommerce_session',1,2); function twf_add_custom_data_to_woocommerce_session( $cart_item_data, $product_id ) { global $woocommerce; session_start(); if(empty($_SESSION['twf_user_custom_datas'])) return $cart_item_data; else { $options = $_SESSION['twf_user_custom_datas']; //Unset our custom session variable unset($_SESSION['twf_user_custom_datas']); if(empty($cart_item_data)) return $options; else return array_merge($cart_item_data, $options); } } |
3. Add the custom data to WooCommerce cart object
WooCommerce creates a cart object to display all the products added to cart. We need to add the custom information in the cart during checkout. So add the information in cart object.
1 2 3 4 5 6 7 8 9 10 11 |
add_filter('woocommerce_get_cart_item_from_session', 'twf_get_user_custom_data_session', 1, 3 ); function twf_get_user_custom_data_session( $item, $values, $key ) { //Check if the key exist and add it to item variable. if (array_key_exists( 'twf_user_custom_datas', $values ) ) { $item['twf_user_custom_datas'] = $values['twf_user_custom_datas']; } return $item; } |
4. Display Custom data in cart and Checkout page
The custom data is already present in cart object, so you can display it in the cart where the product is displayed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
add_filter('woocommerce_checkout_cart_item_quantity','twf_display_custom_data_in_cart',1,3); add_filter('woocommerce_cart_item_price', 'twf_display_custom_data_in_cart',1,3); function twf_display_custom_data_in_cart( $product_name, $values, $cart_item_key ) { global $wpdb; if(!empty($values['twf_user_custom_datas'])) { $return_string = "<table> <tr> <th>" . ucfirst($values['twf_user_custom_datas']['label']) . "</th>" ."<td>" . $values['twf_user_custom_datas']['value'] . "</td> </tr> </table>"; return $return_string; } } |
5. Add custom data as Metadata to Order Items table
We need to store the custom data in our Order Items MetaData table so that admin can view the information entered and deliver the products accordingly.
1 2 3 4 5 6 7 8 9 10 |
add_action('woocommerce_add_order_item_meta', 'twf_add_custom_data_to_order_item_meta',1,2); function twf_add_custom_data_to_order_item_meta( $item_id, $values ) { global $woocommerce,$wpdb; if(!empty($values['twf_user_custom_datas'])){ $twf_user_custom_datas = $values['twf_user_custom_datas']; wc_add_order_item_meta($item_id, 'twf_custom_data', serialize($twf_user_custom_datas)); } } |
6. Remove User Custom Data, if Product is Removed from Cart
We also need to remove the custom data if the user removes the product from cart.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
add_action('woocommerce_before_cart_item_quantity_zero', 'twf_remove_custom_datas_from_cart',1,1); function twf_remove_custom_datas_from_item_meta( $cart_item_key ) { 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['twf_user_custom_datas'] == $cart_item_key ) unset( $woocommerce->cart->cart_contents[ $key ] ); } } |
7. Additional price based on custom data
Sometimes you may need to calculate an additional price based on entered information. So here we can calculate the price.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
add_action( 'woocommerce_before_calculate_totals', 'twf_additional_price', 1, 3 ); function twf_additional_price( $cart_object ) { global $wpdb; foreach ( $cart_object->cart_contents as $key => $value ) { $extra_charge = 0; if(isset($value['twf_user_custom_datas'])){ $extra_charge = 100; } $value['data']->set_price($value['data']->price + $extra_charge); } } |
8. Display the Custom data in Admin’s Order page
By Default, WooCommerce will display the custom information from metadata table. But if you like to format the way it displays it can be done as below.
- Hide the order meta fields
1 2 3 4 5 6 |
add_filter( 'woocommerce_hidden_order_itemmeta', 'twf_hide_order_item_user_custom_meta_field' ); function twf_hide_order_item_user_custom_meta_field( $fields ) { $fields[] = 'twf_user_custom_datas'; //Add all the custom fields here in this array and it will not be displayed. return $fields; } |
- Show the users custom field in a formatted way
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
add_action( 'woocommerce_after_order_itemmeta', 'twf_user_custom_meta_customized_display',10, 3 ); function twf_user_custom_meta_customized_display( $item_id, $item, $product ){ global $wpdb; $all_meta_data = wc_get_order_item_meta( $item_id, 'bc_bike_config', true); if(!empty($all_meta_data)) { $all_meta_data = unserialize($all_meta_data); if(!empty($all_meta_data['twf_user_custom_datas'])) { //You can have you own logic here. $html_string = "<table>"; $html_string .= "<tr> <th>" . ucfirst($all_meta_data['twf_user_custom_datas']['label']) . "</th> <td>". $all_meta_data['twf_user_custom_datas']['value'] ."</td> </tr>"; $html_string .= "</table>"; echo $html_string; } } } |
That’s all we need to complete the process of adding custom information during adding products to cart. We can also add the custom information in the Order Confirmation Email by looking into the hooks provided by wooCommerce.
In case you find something missing please comment below.
* * *
Also, let me know if find the post useful, it motivates me to keep posting more 🙂
13 Comments
Hi;
2018-05-25 15:02:38thanks for this tutorial, but I'm writing a plugin that add multiple items to cart. this plugin has a off option that must apply to every of specified items only. products and off percentage are variable. now I can add items to cart but can't apply off to items. please help me.
If you need help with the development service for the plugin please let us know.
2018-06-22 10:18:12Hi Nikhil,
2017-10-09 05:48:31Thanks for the tutorial!
it would be great if you could share with us also the ajax call you are doing when clicking 'Add to Cart Button". I'm stuck in that last step.
David
Hi David,
2017-10-11 11:31:24The ajax call is simple. On Click of the button make ajax call which will send the product_id, quantity and the custom information you need to save.
Just edited the blog to change the step1, re-read it.
Let me know if you need more information. Or we can help you with implementing this feature email: [email protected]
can i update custom data ?
2017-08-11 00:46:42Yes, you can do it, make sure you understand the above steps. Updating will be similar to this.
2017-08-11 23:12:50Hello, thank you very much for this tutorial. I have not yet been able to make it work, but I did want to mention a few things I noted in your code:
2017-07-29 02:57:14In step 2, the add_filter section is left out of the code sample and is in plain text above it with the description.
In step 3, the function name does not match the filter name.
add_filter('woocommerce_get_cart_item_from_session', 'twf_get_user_custom_data_data_session', 1, 3 );
function bc_get_bike_config_data_session( $item, $values, $key ) {
Should it be this instead?
add_filter('woocommerce_get_cart_item_from_session', 'twf_get_user_custom_data_data_session', 1, 3 );
function twf_get_user_custom_data_data_session( $item, $values, $key ) {
In step 8 there is a missing closing parenthesis ")".
if(!empty($all_meta_data['twf_user_custom_datas'])
{
Hi Cody,
2017-08-02 11:17:31I was using WooCommerce 3.0.1 but updated it to the latest 3.1.1 and everything worked fine.
Can you check if the data is getting saved in session by printing the entire session and debugging it from there?
Hi Nikhil,
2017-08-02 03:19:21Thanks for your reply. I'm currently on WooCommerce Version 3.1.1, and I'm wondering if there's a chance I'm having a WooCommerce version conflict. Do you know up to what Version this code will work on? Many I see work up to Version 2.7. I've implemented the code, but the data from my AJAX call never makes it to the cart, and I'm having a hard time tracking down what is failing.
Thanks in advance!
Hello Cody,
2017-07-29 11:07:32Thank you for letting us know. Edited the post.
What problem you're having making it work?
Thank you very much for this tutorial!
2017-07-10 03:44:37Really saved my ass :)
Thank you, Michael.
2017-07-17 09:54:18