Creating a WooCommerce wishlist functionality involves customizing your WooCommerce store to allow users to save products to a wishlist. Below is a step-by-step guide and an example of how to create a simple WooCommerce wishlist using custom code. This example assumes you are comfortable working with PHP and WordPress hooks.
Step 1: Create a Custom Plugin
- Create a folder for your custom plugin. For example, you can name it
woocommerce-wishlist
. - Inside the folder, create a PHP file, e.g.,
woocommerce-wishlist.php
. - Add the following code to your
woocommerce-wishlist.php
file:<?php /* Plugin Name: WooCommerce Wishlist Description: Add wishlist functionality to your WooCommerce store. Version: 1.0 Author: Your Name */ // Add a "Add to Wishlist" button to product pages function add_to_wishlist_button() { global $product; echo '<a href="#" class="add-to-wishlist" data-product-id="' . $product->get_id() . '">Add to Wishlist</a>'; } add_action('woocommerce_after_add_to_cart_button', 'add_to_wishlist_button'); // Handle AJAX request to add a product to the wishlist function add_to_wishlist() { $product_id = $_POST['product_id']; if ($product_id) { // Check if the user is logged in (you can implement your own logic here) if (is_user_logged_in()) { $user_id = get_current_user_id(); // Get the user's wishlist from user meta $wishlist = get_user_meta($user_id, 'wishlist', true); // Add the product to the wishlist $wishlist[] = $product_id; // Update the user's wishlist in user meta update_user_meta($user_id, 'wishlist', $wishlist); echo 'Product added to your wishlist.'; } else { echo 'Please log in to add products to your wishlist.'; } } wp_die(); } add_action('wp_ajax_add_to_wishlist', 'add_to_wishlist'); add_action('wp_ajax_nopriv_add_to_wishlist', 'add_to_wishlist');
This PHP code is for creating a WooCommerce wishlist plugin. It adds functionality to allow users to add products to their wishlist and handles AJAX requests to add products to the wishlist. Here’s a step-by-step explanation of the code:
- Plugin Information Comments:
- The comments at the beginning of the code provide information about the plugin, such as its name, description, version, and author. This information is used by WordPress to display details about the plugin in the admin area.
- Adding “Add to Wishlist” Button:
- The
add_to_wishlist_button
function is responsible for adding an “Add to Wishlist” button to product pages. - It uses the
woocommerce_after_add_to_cart_button
action hook, which allows the button to be displayed after the “Add to Cart” button. - The button is created with an anchor (
<a>
) element with a class of ‘add-to-wishlist’ and adata-product-id
attribute containing the product’s ID.
- The
- Handling AJAX Request to Add to Wishlist:
- The
add_to_wishlist
function is responsible for handling the AJAX request to add a product to the wishlist. - It retrieves the
product_id
from the POST data sent via AJAX. - It checks if the user is logged in using
is_user_logged_in()
. You can customize this logic to fit your authentication requirements. - If the user is logged in, it gets the user’s wishlist from user meta using
get_user_meta
. - It adds the
product_id
to the wishlist array. - It updates the user’s wishlist in user meta using
update_user_meta
. - It returns a message indicating that the product has been added to the wishlist.
- If the user is not logged in, it returns a message indicating that they need to log in to add products to their wishlist.
- The
- Ajax Action Hooks:
- The code uses two action hooks for AJAX handling:
wp_ajax_add_to_wishlist
: This hook is used for authenticated users (when they are logged in).wp_ajax_nopriv_add_to_wishlist
: This hook is used for non-authenticated users (guests).
- Both hooks are associated with the
add_to_wishlist
function to handle the AJAX requests.
- The code uses two action hooks for AJAX handling:
Step 2: Create JavaScript for AJAX Handling
Create a JavaScript file, e.g., wishlist.js
, and enqueue it in your plugin to handle AJAX requests.
jQuery(function($) { $('.add-to-wishlist').on('click', function(e) { e.preventDefault(); var product_id = $(this).data('product-id'); $.ajax({ type: 'POST', url: ajaxurl, // WordPress AJAX URL data: { action: 'add_to_wishlist', product_id: product_id }, success: function(response) { alert(response); } }); }); });
This jQuery code is designed to handle a click event on elements with the class ‘.add-to-wishlist’ (which are typically “Add to Wishlist” buttons). When a user clicks on such an element, it triggers an AJAX request to add a product to the wishlist. Let’s break down the code step by step:
jQuery(function ($) { ... });
: This code ensures that the enclosed JavaScript runs when the document is ready, making sure that DOM elements are available for manipulation using jQuery.$('.add-to-wishlist').on('click', function (e) { ... });
: This line attaches a click event handler to all elements with the class ‘.add-to-wishlist’. When any of these elements are clicked, the function inside theon
method will be executed.e.preventDefault();
: This line prevents the default behavior of the anchor tag (the click event’s default action). In this context, it prevents the browser from navigating to a new page when the link is clicked. This is important because you want to handle the click event via AJAX without navigating away from the current page.var product_id = $(this).data('product-id');
: This line extracts the ‘product-id’ data attribute value from the clicked element using thedata
method. It assumes that each ‘.add-to-wishlist’ element has a ‘data-product-id’ attribute containing the product’s unique identifier.$.ajax({ ... });
: This code initiates an AJAX request using jQuery’s$.ajax
method. It sends a POST request to the server to perform an action.type: 'POST'
: Specifies that it’s a POST request.url: ajaxurl
: The URL where the AJAX request is sent. This URL should be set to WordPress’s AJAX URL, which is often available asajaxurl
in WordPress scripts. It’s used as the target URL for the AJAX request.data: { action: 'add_to_wishlist', product_id: product_id }
: The data to send with the request includes an ‘action’ parameter set to ‘add_to_wishlist’ (indicating the action to be performed on the server) and the ‘product_id’ extracted from the data attribute.success: function (response) { ... }
: A callback function that executes when the AJAX request is successful. It receives a ‘response’ parameter, which typically contains the server’s response.
alert(response);
: When the AJAX request is successful, it displays the response using an alert dialog. This is a simple way to show feedback to the user. In a real-world application, you might want to update the page’s content dynamically instead of using an alert.
Step 3: Enqueue JavaScript
Enqueue the JavaScript file in your plugin to ensure it’s loaded on the frontend:
function enqueue_wishlist_script() { wp_enqueue_script('wishlist', plugin_dir_url(__FILE__) . 'wishlist.js', array('jquery'), '1.0', true); wp_localize_script('wishlist', 'ajaxurl', admin_url('admin-ajax.php')); } add_action('wp_enqueue_scripts', 'enqueue_wishlist_script');
Step 4: Display the Wishlist
You can create a WooCommerce page for the wishlist or add a custom shortcode to display the user’s wishlist.
function display_wishlist() { if (is_user_logged_in()) { $user_id = get_current_user_id(); $wishlist = get_user_meta($user_id, 'wishlist', true); if (!empty($wishlist)) { echo '<h2>Your Wishlist</h2>'; echo '<ul>'; foreach ($wishlist as $product_id) { $product = wc_get_product($product_id); if ($product) { echo '<li>' . $product->get_title() . ' - <a href="#" class="remove-from-wishlist" data-product-id="' . $product_id . '">Remove</a></li>'; } } echo '</ul>'; } else { echo 'Your wishlist is empty.'; } } else { echo 'Please log in to view your wishlist.'; } } add_shortcode('wishlist', 'display_wishlist');
This PHP code defines a function called display_wishlist
that is intended to be used as a shortcode in WordPress. The shortcode [wishlist]
can be used in posts or pages to display a user’s wishlist if they are logged in. Here’s a step-by-step explanation of the code:
display_wishlist
Function: This function is responsible for displaying the user’s wishlist. It checks whether the user is logged in and, if so, retrieves and displays the wishlist items.if (is_user_logged_in()) { ... }
: This condition checks if the user is logged in usingis_user_logged_in()
. If the user is logged in, it proceeds with displaying the wishlist.else
: If the user is not logged in, it displays a message asking the user to log in to view their wishlist.
- Inside the
if (is_user_logged_in())
block:$user_id = get_current_user_id();
: This line retrieves the current user’s ID usingget_current_user_id()
.$wishlist = get_user_meta($user_id, 'wishlist', true);
: This line fetches the user’s wishlist from user meta. It assumes that the wishlist is stored as an array of product IDs in the user’s meta data under the ‘wishlist’ key.if (!empty($wishlist)) { ... }
: This condition checks if the wishlist is not empty. If there are items in the wishlist, it proceeds to display them.- Inside the
if (!empty($wishlist))
block:echo '<h2>Your Wishlist</h2>';
: This line displays a heading indicating that it’s the user’s wishlist.echo '<ul>';
: It starts an unordered list (<ul>
) to list the wishlist items.foreach ($wishlist as $product_id) { ... }
: It loops through each product ID in the wishlist array.$product = wc_get_product($product_id);
: This line retrieves the product object for the current product ID using WooCommerce’swc_get_product
function.if ($product) { ... }
: This condition checks if the product object exists. If it does, it proceeds to display the product information.echo '<li>' . $product->get_title() . ' - <a href="#" class="remove-from-wishlist" data-product-id="' . $product_id . '">Remove</a></li>';
: This line displays the product title and adds a “Remove” link with the class ‘remove-from-wishlist’ and adata-product-id
attribute containing the product ID. This link can be used to remove the product from the wishlist.
echo '</ul>';
: It closes the unordered list (<ul>
).
- If the wishlist is empty (
else
ofif (!empty($wishlist))
), it displays a message indicating that the wishlist is empty.
- If the user is not logged in (
else
ofif (is_user_logged_in())
), it displays a message asking the user to log in to view their wishlist. - Shortcode Registration: The
add_shortcode('wishlist', 'display_wishlist')
line registers the ‘wishlist’ shortcode in WordPress, associating it with thedisplay_wishlist
function. This allows users to use the[wishlist]
shortcode in their posts or pages to display their wishlist.
Step 5: Handle Removing Products from Wishlist
Add JavaScript and AJAX handling to remove products from the wishlist:
jQuery(function($) { $('.remove-from-wishlist').on('click', function(e) { e.preventDefault(); var product_id = $(this).data('product-id'); $.ajax({ type: 'POST', url: ajaxurl, // WordPress AJAX URL data: { action: 'remove_from_wishlist', product_id: product_id }, success: function(response) { alert(response); location.reload(); // Refresh the page after removing } }); }); });
This jQuery code is designed to handle a click event on elements with the class ‘.remove-from-wishlist,’ which are typically “Remove” links associated with products in a user’s wishlist. When a user clicks on such an element, it triggers an AJAX request to remove a product from the wishlist. Let’s break down the code step by step:
jQuery(function ($) { ... });
: This code ensures that the enclosed JavaScript runs when the document is ready, making sure that DOM elements are available for manipulation using jQuery.$('.remove-from-wishlist').on('click', function (e) { ... });
: This line attaches a click event handler to all elements with the class ‘.remove-from-wishlist.’ When any of these elements are clicked, the function inside theon
method will be executed.e.preventDefault();
: This line prevents the default behavior of the anchor tag (the click event’s default action). In this context, it prevents the browser from navigating to a new page when the “Remove” link is clicked. This is essential because you want to handle the click event via AJAX without navigating away from the current page.var product_id = $(this).data('product-id');
: This line extracts the ‘product-id’ data attribute value from the clicked element using thedata
method. It assumes that each ‘.remove-from-wishlist’ element has a ‘data-product-id’ attribute containing the product’s unique identifier.$.ajax({ ... });
: This code initiates an AJAX request using jQuery’s$.ajax
method. It sends a POST request to the server to perform an action (in this case, removing the product from the wishlist).type: 'POST'
: Specifies that it’s a POST request.url: ajaxurl
: The URL where the AJAX request is sent. This URL should be set to WordPress’s AJAX URL, which is often available asajaxurl
in WordPress scripts. It’s used as the target URL for the AJAX request.data: { action: 'remove_from_wishlist', product_id: product_id }
: The data to send with the request includes an ‘action’ parameter set to ‘remove_from_wishlist’ (indicating the action to be performed on the server) and the ‘product_id’ extracted from the data attribute.success: function (response) { ... }
: A callback function that executes when the AJAX request is successful. It receives a ‘response’ parameter, which typically contains the server’s response.
alert(response);
: When the AJAX request is successful, it displays the response using an alert dialog. This is a simple way to show feedback to the user, such as confirming that the product has been removed from the wishlist.location.reload();
: After removing the product from the wishlist and displaying the alert message, it reloads the page usinglocation.reload()
. This is done to update the display and show the updated wishlist (with the removed product) without requiring a manual page refresh.
Step 6: Handle Removing Products from Wishlist on the Server
Add the server-side code to remove products from the wishlist:
function remove_from_wishlist() { $product_id = $_POST['product_id']; if ($product_id) { if (is_user_logged_in()) { $user_id = get_current_user_id(); $wishlist = get_user_meta($user_id, 'wishlist', true); // Find and remove the product from the wishlist $index = array_search($product_id, $wishlist); if ($index !== false) { unset($wishlist[$index]); $wishlist = array_values($wishlist); // Re-index the array update_user_meta($user_id, 'wishlist', $wishlist); echo 'Product removed from your wishlist.'; } else { echo 'Product not found in your wishlist.'; } } else { echo 'Please log in to remove products from your wishlist.'; } } wp_die(); } add_action('wp_ajax_remove_from_wishlist', 'remove_from_wishlist'); add_action('wp_ajax_nopriv_remove_from_wishlist', 'remove_from_wishlist');
This PHP code defines a function called remove_from_wishlist
that handles the removal of a product from a user’s wishlist. It is intended to be used as an AJAX callback in WordPress. Here’s a step-by-step explanation of the code:
remove_from_wishlist
Function: This function is responsible for removing a product from the user’s wishlist.$product_id = $_POST['product_id'];
: This line retrieves the ‘product_id’ sent as POST data via AJAX. It represents the product that the user wants to remove from their wishlist.if ($product_id) { ... }
: This condition checks if a valid ‘product_id’ was provided via the AJAX request.if (is_user_logged_in()) { ... }
: This nested condition checks if the user is logged in usingis_user_logged_in()
. If the user is logged in, it proceeds with removing the product.$user_id = get_current_user_id();
: This line gets the ID of the currently logged-in user usingget_current_user_id()
.$wishlist = get_user_meta($user_id, 'wishlist', true);
: This line retrieves the user’s wishlist from user meta. It assumes that the wishlist is stored as an array of product IDs in the user’s meta data under the ‘wishlist’ key.- Removing the Product from Wishlist:
$index = array_search($product_id, $wishlist);
: This line searches for the index of the ‘product_id’ in the ‘wishlist’ array. If found, it returns the index; otherwise, it returnsfalse
.if ($index !== false) { ... }
: This condition checks if the product was found in the wishlist.unset($wishlist[$index]);
: If the product is found, it removes it from the ‘wishlist’ array.$wishlist = array_values($wishlist);
: This line re-indexes the ‘wishlist’ array so that it doesn’t have any gaps in the keys.update_user_meta($user_id, 'wishlist', $wishlist);
: It updates the user’s wishlist in user meta with the modified ‘wishlist’ array, which now excludes the removed product.echo 'Product removed from your wishlist.';
: A message is echoed to indicate that the product has been successfully removed from the wishlist.
- If the product is not found in the wishlist (
else
ofif ($index !== false)
), it echoes a message indicating that the product was not found.
- If the user is not logged in (
else
ofif (is_user_logged_in())
), it echoes a message asking the user to log in to remove products from their wishlist.
- Ajax Action Hooks:
- The code uses two action hooks for AJAX handling:
wp_ajax_remove_from_wishlist
: This hook is used for authenticated users (when they are logged in).wp_ajax_nopriv_remove_from_wishlist
: This hook is used for non-authenticated users (guests).
- Both hooks are associated with the
remove_from_wishlist
function to handle the AJAX requests.
- The code uses two action hooks for AJAX handling: