Skip to content

Instantly share code, notes, and snippets.

@mohammadmursaleen
Last active October 15, 2021 18:29
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save mohammadmursaleen/9622098e43afdab6025e to your computer and use it in GitHub Desktop.
Save mohammadmursaleen/9622098e43afdab6025e to your computer and use it in GitHub Desktop.
Adding custom fields above WOOCOMMERCE add to cart button
<?php
// To add custom data above add to cart button in woocommerce
// step 1
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
$custom_data_1 = $_POST['custom_data_1']; //This is User custom value sent via AJAX
$custom_data_2 = $_POST['custom_data_2'];
$custom_data_3 = $_POST['custom_data_3'];
$custom_data_4 = $_POST['custom_data_4'];
$custom_data_5 = $_POST['custom_data_5'];
session_start();
$_SESSION['custom_data_1'] = $custom_data_1;
$_SESSION['custom_data_2'] = $custom_data_2;
$_SESSION['custom_data_3'] = $custom_data_3;
$_SESSION['custom_data_4'] = $custom_data_4;
$_SESSION['custom_data_5'] = $custom_data_5;
die();
}
// step 2
add_filter('woocommerce_add_cart_item_data','wdm_add_item_data',1,2);
if(!function_exists('wdm_add_item_data'))
{
function wdm_add_item_data($cart_item_data,$product_id)
{
/*Here, We are adding item in WooCommerce session with, wdm_user_custom_data_value name*/
global $woocommerce;
session_start();
$new_value = array();
if (isset($_SESSION['custom_data_1'])) {
$option1 = $_SESSION['custom_data_1'];
$new_value['custom_data_1'] = $option1;
}
if (isset($_SESSION['custom_data_2'])) {
$option2 = $_SESSION['custom_data_2'];
$new_value['custom_data_2'] = $option2;
}
if (isset($_SESSION['custom_data_3'])) {
$option3 = $_SESSION['custom_data_3'];
$new_value['custom_data_3'] = $option3;
}
if (isset($_SESSION['custom_data_4'])) {
$option4 = $_SESSION['custom_data_4'];
$new_value['custom_data_4'] = $option4;
}
if (isset($_SESSION['custom_data_5'])) {
$option5 = $_SESSION['custom_data_5'];
$new_value['custom_data_5'] = $option5;
}
if( empty($option1) && empty($option2) && empty($option3) && empty($option4) && empty($option5) )
return $cart_item_data;
else
{
if(empty($cart_item_data))
return $new_value;
else
return array_merge($cart_item_data,$new_value);
}
// vardump($new_value);
// die();
unset($_SESSION['custom_data_1']);
unset($_SESSION['custom_data_2']);
unset($_SESSION['custom_data_3']);
unset($_SESSION['custom_data_4']);
unset($_SESSION['custom_data_5']);
//Unset our custom session variable, as it is no longer needed.
}
}
// step 3
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( 'custom_data_1', $values ) )
{
$item['custom_data_1'] = $values['custom_data_1'];
}
if (array_key_exists( 'custom_data_2', $values ) )
{
$item['custom_data_2'] = $values['custom_data_2'];
}
if (array_key_exists( 'custom_data_3', $values ) )
{
$item['custom_data_3'] = $values['custom_data_3'];
}
if (array_key_exists( 'custom_data_4', $values ) )
{
$item['custom_data_4'] = $values['custom_data_4'];
}
if (array_key_exists( 'custom_data_5', $values ) )
{
$item['custom_data_5'] = $values['custom_data_5'];
}
return $item;
}
}
// step 4
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['custom_data_1']) > 0)
{
$return_string = $product_name . "</a><dl class='variation'>";
$return_string .= "<table class='wdm_options_table' id='" . $values['product_id'] . "'>";
$return_string .= "<tr><td> custom_data_1 : " . $values['custom_data_1'] . "</td></tr>";
$return_string .= "<tr><td> custom_data_2 : " . $values['custom_data_2'] . "</td></tr>";
$return_string .= "<tr><td> custom_data_3 : " . $values['custom_data_3'] . "</td></tr>";
$return_string .= "<tr><td> custom_data_4 : " . $values['custom_data_4'] . "</td></tr>";
$return_string .= "<tr><td> custom_data_5 : " . $values['custom_data_5'] . "</td></tr>";
$return_string .= "</table></dl>";
return $return_string;
}
else
{
return $product_name;
}
}
}
// step 5
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);
}
$custom_data_1 = $values['custom_data_1'];
if(!empty($custom_data_1))
{
wc_add_order_item_meta($item_id,'custom_data_1',$custom_data_1);
}
$custom_data_2 = $values['custom_data_2'];
if(!empty($custom_data_2))
{
wc_add_order_item_meta($item_id,'custom_data_2',$custom_data_2);
}
$custom_data_3 = $values['custom_data_3'];
if(!empty($custom_data_3))
{
wc_add_order_item_meta($item_id,'custom_data_3',$custom_data_3);
}
$custom_data_4 = $values['custom_data_4'];
if(!empty($custom_data_4))
{
wc_add_order_item_meta($item_id,'custom_data_4',$custom_data_4);
}
$custom_data_5 = $values['custom_data_5'];
if(!empty($custom_data_5))
{
wc_add_order_item_meta($item_id,'custom_data_5',$custom_data_5);
}
}
}
// step 6
add_action('woocommerce_before_cart_item_quantity_zero','wdm_remove_user_custom_data_options_from_cart',1,1);
if(!function_exists('wdm_remove_user_custom_data_options_from_cart'))
{
function wdm_remove_user_custom_data_options_from_cart($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['wdm_user_custom_data_value'] == $cart_item_key )
unset( $woocommerce->cart->cart_contents[ $key ] );
}
}
}
?>
// I m using following script in my template which is working perfect
<script type="text/javascript">
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 custom_data_1 = 'custom_data_1';
var custom_data_2 = 'custom_data_2';
var custom_data_3 = 'custom_data_3';
var custom_data_4 = 'custom_data_4';
var custom_data_5 = 'custom_data_5';
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
jQuery.ajax({
url: ajaxurl, //AJAX file path - admin_url('admin-ajax.php')
type: "POST",
data: {
//action name
action:'wdm_add_user_custom_data_options',
custom_data_1 : custom_data_1,
custom_data_2 : custom_data_2,
custom_data_3 : custom_data_3,
custom_data_4 : custom_data_4,
custom_data_5 : custom_data_5
},
async : false,
success: function(data){
//Code, that need to be executed when data arrives after
// successful AJAX request execution
alert('ajax response recieved');
}
});
})
});
</script>
@mohammadmursaleen
Copy link
Author

Right now there is some error or I'm missing something due to which data of only last field ('custom_data_5') is being displayed and working.

@mohammadmursaleen
Copy link
Author

OK issue fixed now we can display all five custom fields. Have updated the above code.

@MuhammadRehman
Copy link

Thanks for this snippet!! Saved my day!! 😄

@paulmoreton
Copy link

Hi, great post - exactly what I've been searching for. However I'm a complete newbie to PHP and WordPress and I'm struggling to get it to work.
I've added the lines 1 to 228 into my functions.php file within my theme directory. Where do I need to add lines 230 to 278? If I need to create a new file, where would I do this? Which template file are you calling the script from? How are you doing this?
Thanks so much in advance for your help
Paul

@CKMacLeod
Copy link

Very useful - challenge however will be write so that varying number of items can be added. In other words, if items are entries in a form, then some users (customer) maybe have five entries to make, others two, other twenty five. Still, though I am not sure that this format will work in a more complex process, it's definitely a start.

@jewelhuq
Copy link

Its very useful tutorial.But i dont know where to add your function.
What i need to do:
1.Add customer field color(for example red,green) & size with drop download menu(25 size,size etc in check box ,so user can select multiple size)

  1. Then i have to show these things custom value in checkout page & need to save save this things in database too.

How can i do it.

@huzeifa88
Copy link

The only problem is its not working on android chrome.
Can any thing be done to add functionality to chrome, it would be huge...
Thanks in advance.

@ambisyoso901
Copy link

Hi,

This is not working if the browser doesn't have a session can you please help?

Thanks.

@allensmilko
Copy link

Hi dude, nice job!!!! This work is awesome !
But you need add
if(!empty($custom_data_1))
{
wc_add_order_item_meta($item_id,'custom_data_1',$custom_data_1);
}

@mohammadmursaleen
Copy link
Author

Thanks Alan!

Have updated my code. :)

@AndreasHnida
Copy link

Absolutely saved my Day!
Thank you very much!

@ntentopoulos
Copy link

ntentopoulos commented Jun 3, 2017

hi there mohammad, it seems like an amazing feauture to woocommerce, but somehow i cant get that to work.
I added before the add-to-cart-button the following fields that need to be placed into the order

<input type="hidden" id="quantity" name="quantity" value="1" /> <input type="hidden" id="custom_data_1" name="custom_data_1" value="<?php echo $elite_sku; ?>" /> <input type="hidden" id="pa_techno_width" name="custom_data_3" value="1" /> <input type="hidden" id="pa_techno_lenght" name="custom_data_4" value="2" /> <input type="hidden" id="pa_techno_price" name="custom_data_5" value="3" />

(i changed the only the first ID to custom_data_1 to match NAME for testing purposes only)

but the result im getting in the cart is :

custom_data_1 : custom_data_1
custom_data_2 : custom_data_2
custom_data_3 : custom_data_3
custom_data_4 : custom_data_4
custom_data_5 : custom_data_5

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

@arslanali222
Copy link

arslanali222 commented Aug 7, 2017

All of you must add this script according to your fields and conditions and also use single_add_to_cart button.
SCRIPT:-

<script type="text/javascript"> jQuery(document).ready(function($){ //code to add validation on "Add to Cart" button jQuery('.single_add_to_cart_button').click(function(){ //alert("I'm Clicked"); //code to add validation, if any //If all values are proper, then send AJAX request var start_from = $('#start_from').val(); var finish_by=$('#finish_by').val(); var location=$('#location').val(); var where_do_we_meet_you=$('#where_do_we_meet_you').val(); var instructor=$('#instructor').val(); var date=$('#date').val(); //alert(start_from); 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', start_from: start_from, finish_by: finish_by, location: location, where_do_we_meet_you: where_do_we_meet_you, instructor: instructor, date: date, }, async : false, success: function(data){ //Code, that need to be executed when data arrives after // successful AJAX request execution //alert('ajax response recieved'); } }); }) }); </script>

Add to Cart Button:-

Add to cart

@joeblackdandt
Copy link

Hello everyone, brad new to WC, does this code work for woocommerce 3+?

@yusraS
Copy link

yusraS commented Sep 20, 2017

Where do I need to write java script code

@tapfumamanhanga
Copy link

I was able to follow the code up to last part with the javascript code and I understand that is what what will make the function in step 1 run. My questioin is: "After running the function in step 1, how do the other functions get called?

@MrShabir
Copy link

MrShabir commented Nov 4, 2017

How to add different meta values .
Like On one button click i want to add
a
b
c
Then on other button click on want to add
e
f
g
Then how i can sort that on cart page with product ID?

@techjaw
Copy link

techjaw commented Oct 31, 2020

Sorry, not work:

if(count($values['custom_data_1']) > 0) Undefine index custom_data_1

help please

@techjaw
Copy link

techjaw commented Oct 31, 2020

I'm giving a solution for woocomerce 3+, for lower versions it's also on this page. https://wisdmlabs.com/blog/add-custom-data-woocommerce-order-2/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment