Using the WooCommerce Product Table Javascript API

WCPT is a nifty plugin to list all your Products in one place and allow users to quickly add them to cart. It works based on DataTables, and can be used with any WooCommerce store.

WooCommerce Product Table has a nice Javascript API and here is how you can use it:

The plugin fires some events when certain things happen

init.wcpt

Fired only once per table. It is fired when the table is initialized for the very first time and has drawn data on it.

draw.wcpt

Fired when the table is drawn. Drawn means the table has finished showing a new set of data (sort, search, load, fresh data fetched).

load.wcpt

Similar to init, but happens inside window.load, but the drawing doesn’t happen in here.

adding_to_cart

When the plugin is trying to add something to the cart, when you click the button for it, this is fired.

added_to_cart

When adding is completed. You can use this to redirect users to the checkout page without using the Redirect plugin, as suggested by their FAQ.

The others like lazyload.wcpt or responsive-display.wcpt are fired when their respective function is fired.

How to use the API?

All of these events are attached to the body and they pass a ProductTable  parameter inside them, which is the related table to the event.

To use them, simply do (we’re using jQuery here):

$('body').on('draw.wcpt', function(table){
    // your code here, and it will fire when draw.wcpt is fired
    // use the variable table to fetch data from the table or make it do something
});

That’s it! The browser will now wait for that event and will start executing the code inside when it does.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.