Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save AjayAjaal/75255dad7c6f8c6b6ce3 to your computer and use it in GitHub Desktop.
Save AjayAjaal/75255dad7c6f8c6b6ce3 to your computer and use it in GitHub Desktop.
<script type="text/javascript">
jQuery(document).ready(function(){
/*jQuery firing on add to cart button click*/
jQuery('.single_add_to_cart_button').click(function(){
/*Product meta data being sent; this is where you'd do your
document.getElementsByName or .getElementById*/
var product-meta-data = 'product-meta-data';
/*Ajax request URL being stored*/
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
jQuery.ajax({
url: ajaxurl,
type: "POST",
data: {
//action name (must be consistent with your php callback)
action:'custom_data',
product-meta-data : product-meta-data,
},
async : false,
success: function(data){
/*if sucessful alert us, show data sent to the server*/
alert("We did it" + data);
}
});
})
});
</script>
<?php
add_action('wp_ajax_custom_data', 'custom_data_callback');
add_action('wp_ajax_nopriv_custom_data', 'custom_data_callback');
// The call back function, basically the code that recives the values sent
function custom_data_callback() {
// We'll use this to post back the data the server received
print_r($_POST);
// Lets store the data in the current session
session_start();
$_SESSION['custom_meta_data'] = $_POST['custom_meta_data'];
// RIP
die();
}
//captures additional posted information (all sent in one array)
add_filter('woocommerce_add_cart_item_data','add_item_data',1,10);
function add_item_data($cart_item_data, $product_id) {
// get the woocommerce object
global $woocommerce;
// Save values in an array to add to cart data
$new_value = array();
// move the values from the session into the array
$new_value['custom_meta_data'] = $_SESSION['custom_meta_data'];
// make sure the old values in the array don't get lost
if(empty($cart_item_data)) {
return $new_value;
} else {
return array_merge($cart_item_data, $new_value);
}
}
// we make use of the values stored in the array previously and attach it to the item.
add_filter('woocommerce_get_cart_item_from_session', 'get_cart_items_from_session', 1, 3 );
function get_cart_items_from_session($item,$values,$key) {
// add the custom meta data to the item
if (array_key_exists( '_custom_options', $values ) ) {
$item['custom_meta_data'] = $values['custom_meta_data'];
}
return $item;
}
// displays extra information in the basket along with the product name
add_filter('woocommerce_cart_item_name','add_user_custom_session',1,3);
function add_user_custom_session($product_name, $values, $cart_item_key ) {
// display the custom meta data in the basket
$return_string = $product_name . "<br />" . $values['_custom_options']['custom_meta_data'];
return $return_string;
}
// This adds the information as meta data so that it can be seen as part of the order
// if you want to hide any meta data from the customer just start it with an underscore
add_action('woocommerce_add_order_item_meta','add_values_to_order_item_meta',1,2);
function add_values_to_order_item_meta($item_id, $values) {
// woo and wo stuff
global $woocommerce,$wpdb;
// lets add the meta data to the order!
wc_add_order_item_meta($item_id,'custom_meta_data', $values['custom_meta_data']);
}
// Lastly lets get rid of all of the meta data when an product is removed from the basket/cart
add_action('woocommerce_before_cart_item_quantity_zero','remove_user_custom_data_options_from_cart',1,1);
function remove_user_custom_data_options_from_cart($cart_item_key) {
// Bring me the woocomerce stuffs
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 ] );
}
}
?>
@brettmcdade
Copy link

Hi Ajay.

I'm having a tough go at trying to implement this for my situation. What I would like to do is pass the values from the select boxes (Campus Location, Class, and Orientation Code) to add_cart_item_data. Example: http://redonkhost.com/kdprep

Currently I am just trying to pass a string to see if I can get it to work but I'm getting back a "0" from the ajax success response and nothing is happening in cart.

script.js

    jQuery(document).ready(function(){
        //code to add validation on "Add to Cart" button
        jQuery('#js-add-to-cart').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 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:'custom_data_callback',
                    custom_data_1 : custom_data_1

                },
                async : false,
                success: function(data){
                    //Code, that need to be executed when data arrives after
                    // successful AJAX request execution

                    alert('ajax response recieved' + data);


                }
            });
        })
    });

sample.php

<?php

add_action('wp_ajax_custom_data', 'custom_data_callback');
add_action('wp_ajax_nopriv_custom_data', 'custom_data_callback');
// The call back function, basically the code that recives the values sent
function custom_data_callback() {
    // We'll use this to post back the data the server received
    print_r($_POST);
    // Lets store the data in the current session
    session_start();
    $_SESSION['myCustomData']  = $_POST['custom_data_1']; 
    // RIP
    die();
}


// Add data to cart
// http://stackoverflow.com/questions/25188365/how-to-retrieve-cart-item-data-with-woocommerce


/*
add_filter( 'woocommerce_add_cart_item_data', function ( $cartItemData, $productId, $variationId ) {
    $cartItemData['myCustomData'] = $_GET['link'];

    return $cartItemData;
}, 10, 3 );
*/
//captures additional posted information (all sent in one array)
    add_filter('woocommerce_add_cart_item_data','add_item_data',1,10);
    function add_item_data($cart_item_data, $product_id) {
        // get the woocommerce object
        global $woocommerce;
        // Save values in an array to add to cart data
        $new_value = array();
        // move the values from the session into the array
        $new_value['myCustomData'] = $_SESSION['myCustomData'];
        // make sure the old values in the array don't get lost
        if(empty($cart_item_data)) {
            return $new_value;
        } else {
            return array_merge($cart_item_data, $new_value);
        }
    }





add_filter( 'woocommerce_get_cart_item_from_session', function ( $cartItemData, $cartItemSessionData, $cartItemKey ) {
    if ( isset( $cartItemSessionData['myCustomData'] ) ) {
        $cartItemData['myCustomData'] = $cartItemSessionData['myCustomData'];
    }

    return $cartItemData;
}, 10, 3 );


// Show data at cart/checkout
add_filter( 'woocommerce_get_item_data', function ( $data, $cartItem ) {
    if ( isset( $cartItem['myCustomData'] ) ) {
        $data[] = array(
            'name' => 'My custom data',
            'value' => $cartItem['myCustomData']
        );
    }

    return $data;
}, 10, 2 );


// Save data
add_action( 'woocommerce_add_order_item_meta', function ( $itemId, $values, $key ) {
    if ( isset( $values['myCustomData'] ) ) {
        wc_add_order_item_meta( $itemId, 'myCustomData', $values['myCustomData'] );
    }
}, 10, 3 );

?>

Thanks for any help

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