Skip to main content

Using JavaScript Hooks

JavaScript hooks were introduce in WordPress version 5.0 with the advent of the highly anticipated Gutenberg release. These hooks are very similar to the standard PHP hooks that WordPress developers have been familiar with for years.

Like PHP hooks, these JavaScript-based hooks allow you to "filter" data and listen to unique "actions". This guide won't be a comprehensive tutorial on how to use WordPress hooks. For that, please take a look at the official WordPress documentation first.

ShopWP provides many JavaScript hooks allowing you to hook into various parts of the plugin. This enables you to do things such as detect when the cart opens, or when the user clicks the checkout button. You can then run your own code from a callback function to make any customizations you want. Let's see how this works.

Setting things up

ShopWP injects its JavaScript in the footer to improve performance. However, it's possible that your theme's JavaScript may run before ShopWP. If this occurs, none of the custom JavaScript hooks you write will work.

To get around this, be sure to set shopwp-public as a dependency in your theme's wp_enqueue_script. Like this:

function theme_assets() {
wp_enqueue_script( 'your-js', '<your-path>/scripts.js', ['shopwp-public'], '', true);
}

add_action('wp_enqueue_scripts', 'theme_assets');

Adding actions

Let's say we want to detect when a product is added to the cart. We can do this by hooking into the on.afterAddToCart action like this:

wp.hooks.addAction('on.afterAddToCart', 'shopwp', function (lineItem, variant) {
// Do something after adding to cart ...
console.log('lineItem :: ', lineItem)
console.log('variant :: ', variant)
})

The on.afterAddToCart action is given two parameters lineItem and variant that you can inspect. Each hook will have useful parameters like this to aid you along the way.

We've listed all of the available JavaScript hooks in this documentation.

Adding filters

The JavaScript filters can provide a lot of flexibility when it comes to the product layout. Many of these filters will allow you to add raw HTML before or after various components of the layout.

For example, let's say we want to add the product vendor name before the product title. We can do this by hooking into the before.productTitle filter. We have access to a "props" argument which we can use like this:

wp.hooks.addFilter(
'before.productTitle',
'shopwp',
function (defaultValue, props) {
return '<p>Vendor: ' + props.product.vendor + '</p>'
}
)

List of available hooks

Actions

Filters