How to Create Your Own AJAX WooCommerce Wishlist Plugin

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 with
the name “wishlist” and a PHP file with the same name. Add the following snippet to the
PHP 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 pages
    using WooCommerce hooks
  • Create wishlist table shortcode to hold the products added
    to 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. So
right 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.js
file for the plugin, also we pass some parameters to the main.js file to work
with:

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

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

So for now create a css, and js folder and put the corresponding
files 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 and
to each single product layout, using the woocommerce_before_shop_loop_item_title
and woocommerce_single_product_summary
hooks.

Here I want to point out the data-product attribute that
contains 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 the
animation. 

3. Add SVG Icons

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

If you are new
to 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 and
paste the following code:

The logic here is as follows: 

  1. Initially we show the
    heart path of our SVG.
  2. When the user clicks on it we will hide the heart path
    and show the loading path.
  3. Once the loading finishes we will show the checkmark
    indicating 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 shortcode
creation process, but if you are new to this, I highly recommend reading this
amazing 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 will
remove the loading class with JavaScript later, once the wishlist items are ready to be
appended to the table. But for now open the style.css and add the following
code:

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 loading
SVG.

Now, if you go to the wishlist page and refresh it you will
see 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 users
and 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 the
session storage

You can also store the guest users’ wishlist in local
storage
, the difference being that session storage is destroyed when the user closes
the tab or browser, and local storage is destroyed when the browser cache
is 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 reading
this amazing tutorial:

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

So once the wishlist is updated it
will save to the database. I you go to your profile page you will see a
new text field added to it. Add whatever value you want and hit save to test if the
update functionality works. With admin CSS you can hide this field if you don’t
want 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 passed
some parameters to it. Here, with JavaScript, we can collect these parameters.

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

Let me explain the logic here: whenever the user visits the
shop 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, and
if so highlight these items. If not we need to see if there are any items in the session/local
storage 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 in
the profile wishlist, we will need to show the ones that he or she added before
login, 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 explain
our helper functions. I won’t describe in detail the AJAX functionality in
WordPress, but if you are new to AJAX and WordPress, I highly
recommend reading this amazing tutorial on it:

Our first AJAX request gets the user id and the user
wishlist data from WordPress. This is done with a custom AJAX action added to the
plugin 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 user
wishlist 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 url
option–see it is different.

The logic is the same
as for the first action–the difference is that here we don’t return or echo
any 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 our
helper 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 next
function executes when an item is added to the wishlist and the last
one shows items that are in the wishlist.

Add Toggle

Now let’s add a click event to the wishlist toggle to power
the actual functionality. On each toggle click event the
animation is triggered and if the user is logged-in the wishlist update action
fires with AJAX. If the user is a guest the item is added to the
session/local storage. 

Now if you go to the shop page, refresh the browser, and
click 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 wishlist
table we created earlier.

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

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

For
each of the products we get we are adding a table row with the required data to
display. 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 present
in the Woocommerce REST API, but an API key is required. With the default
WordPress REST API product data is absent by default, but can be added, and no
API key is required. For such a simple task as a wishlist I don’t think that an API
key 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 the
following code:

All this does is create new fields for REST API and extends the
maximum 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 the
page you will see the list of items that are added to your wishlist. 

8. Removing Items From Wishlist

We are almost
done; only the remove functionality remains. So let’s create that! Add the
following 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 whatever
icon you want), we need to check if the user is logged-in. If so, we then remove the
item ID from the wishlist using AJAX with the user_wishlist_update
action. If the user is a guest we need to remove the item ID from the
session/local storage.

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

Conclusion

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 can
extend, 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!



Source link

https://avasta.ch

Leave a Comment

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

*
*