Black Friday

30% off premium pluginsEnds 2 December

Shop the sale
Simple Wishlists

How can we help?

Search the documentation or ask the AI agent anything about the plugin.

JavaScript API and events

Simple WishlistsUpdated

The storefront script exposes a window.swlp object and fires document events when the wishlist changes. Use them to react to saves in your theme, read the visitor’s wishlist state, or show your own notifications. The script is plain JavaScript and does not need jQuery.

The swlp object

  • swlp.state: the visitor’s state: keys, items (each with id, key and list), count and lists (each with id, title, count and isDefault).
  • swlp.ready( fn ): runs fn once the state has loaded, or straight away when nothing needs loading.
  • swlp.has( productId, variationId ): whether a product (or variation) is saved.
  • swlp.toast( message, opts ): shows a notification. opts can have type (success or error), link ({ url, text }), undo (a function), image and timeout.
  • swlp.announce( text ): reads a message to screen reader users.
  • swlp.request( action, data, callback ): sends a request to one of the plugin’s wc-ajax endpoints. The security token is added for you. The callback receives ( error, data ).
  • swlp.config: the settings and text passed from PHP (filter: swlp_frontend_data).

Events

Events are fired on document as CustomEvents. The data is in event.detail.

  • swlp:state: the state has loaded or changed.
  • swlp:added: a product was saved.
  • swlp:removed: a product was removed.
  • swlp:before-toggle: fires before a save and can be cancelled with event.preventDefault(). Call event.detail.proceed( listId, extraData ) later to continue the save. PRO uses this to show the “save to which list” popover.

Example

// JavaScript: update your own header badge when the count changes.
document.addEventListener( 'swlp:state', function () {
	var badge = document.querySelector( '.my-wishlist-badge' );
	if ( badge && window.swlp ) {
		badge.textContent = window.swlp.state.count;
	}
} );

// JavaScript: track saves in your analytics tool.
document.addEventListener( 'swlp:added', function ( event ) {
	console.log( 'Saved to wishlist', event.detail );
} );

When the state loads

To keep pages cacheable, the state is loaded with one request, and only for logged-in visitors or visitors with the swlp_has_items cookie. For other visitors swlp.state.count is 0 and swlp.ready() runs straight away.

Related

Was this article helpful?