Your Web News in One Place
November 8, 2019 09:58 am

How to Create Your Own AJAX WooCommerce Wishlist Plugin

In this tutorial we will create lightweight wishlist functionality for WooCommerce using AJAX, WordPress REST API, and SVG graphics. WooCommerce doesn’t come with wishlist functionality as standard, so you’ll always need to rely on an extension to do the work for you. Unless you build it yourself for complete control..

Wish Upon a Star

Wishlist functionality will allow users to mark certain products, adding them to a list for future reference. In some eCommerce stores (such as Amazon) multiple wishlists can be created, and these can be shared with others, which makes them ideal for birthdays or weddings. In our case, the WooCommerce wishlist we’re going to create will enable customers to easily revisit products they’re considering.

Our wishlist functionality will add a heart icon to the product thumbs, which when clicked will add the product to a wishlist in a table.

woocommerce wishlist solution
Click the heart icon to add a product to the wishlist

Take a look at the demo for a proper idea of how it works.

1. Create the Plugin Structure

Let’s start by building our plugin. Create a folder withthe name “wishlist” and a PHP file with the same name. Add the following snippet to thePHP file:

We won’t go into detail about the plugin creation process, but if you are new to plugin development I highly recommend this amazing new course by Rachel McCollin:

Add the Plugin Functions

Let’s sketch out our plan so we know what to build:

  • Add wishlist toggle to products in loop and single pagesusing WooCommerce hooks
  • Create wishlist table shortcode to hold the products addedto the wishlist
  • Create wishlist custom option in the user profile

All the plugin code will go inside the init action for the plugin, as we first need to make sure that the WooCommerce plugin is active. Soright after the plugin details add the following code:

And now let’s enqueue our plugin scripts and styles.

Add the following code to the main plugin file:

Here we enqueue the main style.css file and the main.jsfile for the plugin, also we pass some parameters to the main.js file to workwith:

  • ajaxUrl – required to fetch some data from WordPress, like currentUser ID
  • ajaxPost – required to update user wishlist
  • restUrl – required to list the wishlist items in thewishlist table
  • shopName – required to add wishlist items to the sessionstorage for non-registered or non-logged-in users

And some strings instead of hardcoding them into the js file, in casethey need to be translatable.

So for now create a css, and js folder and put the correspondingfiles inside those folders: style.css in the css folder and main.js in the js folder.

2. Hook the Wishlist Toggle

Right inside the init action add the following code:

Here we add a wishlist toggle to each product in the loop andto each single product layout, using the woocommerce_before_shop_loop_item_titleand woocommerce_single_product_summaryhooks.

Here I want to point out the data-product attribute thatcontains the product ID–this is required to power the wishlist functionality.And also take a closer look at the SVG icon–this is required to power theanimation. 

3. Add SVG Icons

Now create an images folder in the plugin folder and put thefollowing icon.svg in it:

If you are newto working with SVGs I highly recommend you read these amazing tutorials on the subject:

Our SVG animation has 3 states:

  1. Default: the heart path
  2. Process: loading group (g tag)
  3. End: check group (g tag)

If you now go to your shop page you will see the unstyled SVG icons piled on top of each other:

unstyled svg icons

Let’s add some styling to fix this mess! Open the style.css file andpaste the following code:

The logic here is as follows: 

  1. Initially we show theheart path of our SVG.
  2. When the user clicks on it we will hide the heart pathand show the loading path.
  3. Once the loading finishes we will show the checkmarkindicating that the product was successfully added to the wishlist.

We will toggle the loading state via JavaScript later; the loading animation is a simple transform rotate. So for now if you refresh the page (don’t forget to clear the browser cache as sometimes old styles are cached) you will see a nice heart icon with each product. 

This toggle currently does nothing, so we’ll sort that out. But for now let’s keep with our plan.

4. Create Wishlist Table Shortcode

Add the following code in the init plugin action:

This is a very simple shortcode that you can add to any page,and the wishlist items will appear inside it. I won’t describe the shortcodecreation process, but if you are new to this, I highly recommend reading thisamazing tutorial:

Make a Wishlist Page

Now from inside the WP admin create a page called “Wishlist” and put the [wishlist] shortcode inside it. Now if you go to the wishlist page you will see an empty table.

Did you notice the loading class on the table? We willremove the loading class with JavaScript later, once the wishlist items are ready to beappended to the table. But for now open the style.css and add the followingcode:

Add the loading.svg image to the images folder:

This is the same loading SVG separated from the main icon.svg.We could use SVG sprites, but I decided to stick with a separate loadingSVG.

Now, if you go to the wishlist page and refresh it you willsee an empty table with loading on it. Nice, let’s move further.

5. Wishlist Custom Option in the User Profile

Our wishlist functionality will work both for logged-in usersand guest users. With logged-in users we’ll store the wishlist information in the user’s metadata, and with guest users we’ll store the wishlist in thesession storage

You can also store the guest users’ wishlist in localstorage, the difference being that session storage is destroyed when the user closesthe tab or browser, and local storage is destroyed when the browser cacheis cleared. It is up to you which option you use for guest users.

Now add the following code to the init action:

Again, in order to remain within the scope of this tutorial, I won’t explain how to work with user metadata. If you are new to this I highly recommend readingthis amazing tutorial:

All we do here is create a text field input that will holdthe wishlist items comma-separated IDs. With show_user_profile and edit_user_profileactions we add the structure of the input field, and with personal_options_update and edit_user_profile_updateactions we power the save functionality. 

So once the wishlist is updated itwill save to the database. I you go to your profile page you will see anew text field added to it. Add whatever value you want and hit save to test if theupdate functionality works. With admin CSS you can hide this field if you don’twant users to see it. I will leave it as is.

6. Turn it On!

Now we are ready to power everything up!

Open the main.js file and put the following code in it:

All our code will go inside this function.

Now let’s gather the required data and create some variables:

As you might remember when we enqueued our main.js script we passedsome parameters to it. Here, with JavaScript, we can collect these parameters.

Next, we will create an empty wishlist array that willcontains wishlist items. We will need the session storage data with our shopname (the ls variable stands for local storage), and we will need to know if theuser is guest or logged-in.

Let me explain the logic here: whenever the user visits theshop page we will need to know if he or she is logged-in or is a guest-user. If the user is logged-in we will need to check if he or she has wishlist items, andif so highlight these items. If not we need to see if there are any items in the session/localstorage and highlight those. 

Why this is done like this? Imagine,if the user first visits the website as a guest, adds items to the wishlist, and then decides to login. If the user does not have items registered inthe profile wishlist, we will need to show the ones that he or she added beforelogin, that are stored in the session/local storage.

So let’s do that step by step:

If User is Logged-in

  • Fetch current user data with AJAX
  • If success update the wishlist
  • Highlight the wishlist items
  • Remove the session/local storage
  • If fail show error message in the console for the developer

If User is Guest

Fetch wishlist from the session/local storage

As you may have noticed here we have double-AJAX and some helper functions.So first let’s create the actions of the AJAX requests, and after that I will explainour helper functions. I won’t describe in detail the AJAX functionality inWordPress, but if you are new to AJAX and WordPress, I highlyrecommend reading this amazing tutorial on it:

Our first AJAX request gets the user id and the userwishlist data from WordPress. This is done with a custom AJAX action added to theplugin code file:

The most important part here is the action name (fetch_user_data)–make sure it is the same for AJAX and for functions wp_ajax_fetch_user_data and wp_ajax_nopriv_fetch_user_data.Here we’re preparing JSON formatted data with user ID and userwishlist data.

Our next AJAX request updates the user wishlist if there were already wishlist items from session/local storage. Take a close look at the urloption–see it is different.

The logic is the sameas for the first action–the difference is that here we don’t return or echoany data, but we update the wishlist option for the current user.

And if our user is a guest we will need to check if there are any wishlist details in the session/local storage.

Helper Functions

Before we move to the events part I want to explain ourhelper functions

The first helper function makes the array unique, by removing duplicates,the second one checks if the given value is present in the given array. The nextfunction executes when an item is added to the wishlist and the lastone shows items that are in the wishlist.

Add Toggle

Now let’s add a click event to the wishlist toggle to powerthe actual functionality. On each toggle click event theanimation is triggered and if the user is logged-in the wishlist update actionfires with AJAX. If the user is a guest the item is added to thesession/local storage. 

Now if you go to the shop page, refresh the browser, andclick on any wishlist toggle you will see it is working!

7. List Items in Wishlist Table

Now it is time to list our wishlist items in the wishlisttable we created earlier.

Add the following code into main.js at the very bottom ofour wrapper function:

Here we are using theWordPress REST API to get the products by ID in the wishlist array. 

Foreach of the products we get we are adding a table row with the required data todisplay. We need the product image, title, stock status, button and price. 

Here we have two options for the REST API: 

  1. using the WordPress REST API 
  2. using the WooCommerce REST API. 

The difference here is that product data is already presentin the Woocommerce REST API, but an API key is required. With the defaultWordPress REST API product data is absent by default, but can be added, and noAPI key is required. For such a simple task as a wishlist I don’t think that an APIkey is needed, so we will do it by extending the default WordPress REST API to return our product price, image code and the stock level.

Go to the main plugin file and at the very bottom add thefollowing code:

All this does is create new fields for REST API and extends themaximum items limit per request. Again, if you are new to this subject I highly recommend reading this series.

For now, if you go to your wishlist table and refresh thepage you will see the list of items that are added to your wishlist. 

8. Removing Items From Wishlist

We are almostdone; only the remove functionality remains. So let’s create that! Add thefollowing code at the very bottom of the wrapper function in the main.js file

Once the remove icon is clicked (make sure you have a remove.svg in the images folder, you can use whatevericon you want), we need to check if the user is logged-in. If so, we then remove theitem ID from the wishlist using AJAX with the user_wishlist_updateaction. If the user is a guest we need to remove the item ID from thesession/local storage.

Now go to your wishlist and refresh the page. Once you clickon the remove icon your item will be removed from the wishlist.


That was quite a project! A simple, but comprehensive wishlist feature for your WooCommerce stores. You are free to use this plugin in any project; you canextend, modify it and make suggestions. I hope you liked it. Here is the link to the source files on GitHub. And here is the demo.

Learn More WooCommerce Theme Development

At Tuts+ we have a great collection of tutorials and courses to learn WooCommerce development. Check out these four great courses to get started!

Original Link:

Share this article:    Share on Facebook
View Full Article

TutsPlus - Code

Tuts+ is a site aimed at web developers and designers offering tutorials and articles on technologies, skills and techniques to improve how you design and build websites.

More About this Source Visit TutsPlus - Code