Skip to content

Instantly share code, notes, and snippets.

@malachi358
Created November 25, 2013 13:27
Show Gist options
  • Save malachi358/7641155 to your computer and use it in GitHub Desktop.
Save malachi358/7641155 to your computer and use it in GitHub Desktop.
Ajax Update Cart Items(Mini Cart) via function.php for WPEC
/**
* add a custom AJAX request handler
*/
function theme_wpsc_cart_update() {
$data = array(
'cart_count' => wpsc_cart_item_count(),
'cart_total' => wpsc_cart_total_widget(),
);
echo json_encode($data);
exit;
}
add_action('wp_ajax_theme_wpsc_cart_update', 'theme_wpsc_cart_update');
add_action('wp_ajax_nopriv_theme_wpsc_cart_update', 'theme_wpsc_cart_update');
/**
* add JavaScript event handler to the page footer
*/
function theme_wpsc_footer() {
if (!is_admin()) {
?>
<script>
jQuery(function($) {
/**
* catch WP e-Commerce cart update event
* @param {jQuery.Event} event
*/
$(document).on("wpsc_fancy_notification", function(event) {
updateMinicart();
});
/**
* catch AJAX complete events, to catch clear cart
* @param {jQuery.Event} event
* @param {jqXHR} xhr XmlHttpRequest object
* @param {Object} ajaxOpts options for the AJAX request
*/
$(document).ajaxComplete(function(event, xhr, ajaxOpts) {
// check for WP e-Commerce "empty_cart" action
if ("data" in ajaxOpts && ajaxOpts.data.indexOf("action=empty_cart") != -1) {
updateMinicart();
}
});
/**
* submit AJAX request to update mini-cart
*/
function updateMinicart() {
// ask server for updated data
$.ajax({
url: "<?php echo admin_url('admin-ajax.php'); ?>",
cache: false,
dataType: "json",
data: { action: "theme_wpsc_cart_update" },
success: function(data) {
// update our mini-cart elements
$("#theme-checkout-count").html(data.cart_count);
$("#theme-checkout-total").html(data.cart_total);
}
});
}
});
</script>
<?php
}
}
add_action('wp_footer', 'theme_wpsc_footer');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment