Menu

Snippets

Yet another programmer blogging about code

Add custom JavaScript actions to wp-e-commerce cart updates

I just stared in horror wonder at the wp-e-commerce script that handles cart updates. Wow. Just… wow. Forget any thought of nicely hooking into that to add some extra client-side actions, it’s a mess and looks like it will probably get worse before it gets better. But fortunately, there is another way.

Update: for WP e-Commerce 3.8.11 and later, there is a new procedure

By staring instead at the function wpsc_add_to_cart() in the ajax.functions.php file, I can see that it generates some script and sends that to the browser to be executed. Apparently, nobody has heard of JSON or JSONP, or triggering custom jQuery events, or… but I digress. At the bottom of that function, after it spits out its script for replacing the cart with a complete new copy, there’s a hook!

do_action( 'wpsc_alternate_cart_html', $cart_messages );

What this means is that any additional script you want to run can be dropped into this hook, letting you tell the browser to, say, update a mini-cart in the page header like so:

EDIT: initially the code below had the function declared as public, because I copied it here from a class; public is now removed, so if you tried this code and got an error, please try again!

/**
* action hook for wp-e-commerce to provide our own AJAX cart updates
*/
function theme_cart_update() {
    $cart_count = wpsc_cart_item_count();
    $total = wpsc_cart_total_widget();
    echo <<<HTML
jQuery("#theme-checkout-count").html("$cart_count");
jQuery("#theme-checkout-total").html("$total");

HTML;
}

add_action('wpsc_alternate_cart_html', 'theme_cart_update');

I actually didn’t go for this in the end because I decided to just toss the standard cart widget in favour of a simpler one, thus reducing the size of the AJAX response considerably. But for the next website that needs both a cart widget and a count/total in the page header, job is already done.