Creating a WooCommerce cart widget involves adding a piece of code to your WordPress theme’s files or using a custom plugin. Here’s an example of how you can create a simple WooCommerce cart widget in WordPress:
Step 1: Create a custom WordPress plugin (Optional)
If you prefer not to modify your theme directly, you can create a custom WordPress plugin to add the cart widget.
- Create a folder for your plugin, e.g.,
woocommerce-cart-widget
. - Inside the folder, create a PHP file, e.g.,
woocommerce-cart-widget.php
. - Add the following code to your
woocommerce-cart-widget.php
file:<?php /* Plugin Name: WooCommerce Cart Widget Description: Display a WooCommerce cart widget. Version: 1.0 Author: Your Name */ // Enqueue the script and style for the cart widget function enqueue_woocommerce_cart_widget_scripts() { if (class_exists('WooCommerce')) { wp_enqueue_script('woocommerce-cart-widget', plugins_url('/js/woocommerce-cart-widget.js', __FILE__), array('jquery'), null, true); wp_localize_script('woocommerce-cart-widget', 'wc_cart_widget_params', array( 'ajax_url' => admin_url('admin-ajax.php'), 'wc_ajax_url' => WC()->ajax_url(), 'cart_url' => wc_get_cart_url(), 'is_cart' => is_cart(), )); wp_enqueue_style('woocommerce-cart-widget', plugins_url('/css/woocommerce-cart-widget.css', __FILE__)); } } add_action('wp_enqueue_scripts', 'enqueue_woocommerce_cart_widget_scripts'); // Add the cart widget to a WordPress widget area function woocommerce_cart_widget() { if (class_exists('WooCommerce')) { echo '<div class="woocommerce-cart-widget">'; the_widget('WC_Widget_Cart', 'title='); echo '</div>'; } } add_action('widgets_init', 'register_woocommerce_cart_widget'); // Register the widget function register_woocommerce_cart_widget() { register_widget('WC_Widget_Cart'); } // AJAX update the cart widget function woocommerce_cart_update() { global $woocommerce; $woocommerce->cart->calculate_totals(); echo json_encode(array( 'cart_count' => WC()->cart->cart_contents_count, 'cart_total' => WC()->cart->get_cart_total(), )); die(); } add_action('wp_ajax_woocommerce_cart_update', 'woocommerce_cart_update'); add_action('wp_ajax_nopriv_woocommerce_cart_update', 'woocommerce_cart_update'); ?>
Let’s break down the code and explain each part:
- Plugin Information:
- 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.
- Enqueueing Scripts and Styles:
- The
enqueue_woocommerce_cart_widget_scripts
function is responsible for enqueuing the necessary JavaScript and CSS files for the cart widget. - It checks if the WooCommerce plugin is active (by checking if the
WooCommerce
class exists) before enqueuing the scripts and styles. - JavaScript and CSS files are enqueued using
wp_enqueue_script
andwp_enqueue_style
functions, respectively. These files are located in the plugin’s/js
and/css
directories.
- The
- Localizing JavaScript Variables:
- The
wp_localize_script
function is used to pass data from PHP to JavaScript. In this case, it’s passing an array of parameters to the JavaScript script named ‘woocommerce-cart-widget’. - These parameters include AJAX URLs, cart URL, and a flag indicating whether the current page is the cart page.
- The
- Adding the Cart Widget to a Widget Area:
- The
woocommerce_cart_widget
function adds the cart widget to a WordPress widget area. - It checks if WooCommerce is active before displaying the widget. If WooCommerce is active, it creates a
<div>
element with the class ‘woocommerce-cart-widget’ and then adds the cart widget usingthe_widget('WC_Widget_Cart', 'title=')
.
- The
- Registering the Widget:
- The
register_woocommerce_cart_widget
function registers the cart widget so that it can be added to widget areas. - It uses the
register_widget
function and specifies ‘WC_Widget_Cart’ as the widget class to be registered.
- The
- AJAX Cart Updates:
- The
woocommerce_cart_update
function is used for AJAX cart updates. - It calculates the cart totals, including the cart count and total price.
- It then encodes these values into a JSON response and sends it to the client.
- The
die()
function is used to terminate the script execution after sending the JSON response.
- The
- AJAX Action Hooks:
- Two action hooks, ‘wp_ajax_woocommerce_cart_update’ and ‘wp_ajax_nopriv_woocommerce_cart_update’, are used to handle the AJAX requests for cart updates. ‘wp_ajax_’ is used for authenticated users, and ‘wp_ajax_nopriv_’ is used for non-authenticated users (guests).
Step 2: Create JavaScript and CSS Files
Inside your plugin folder, create a js
folder and a css
folder. Then, create the following files:
js/woocommerce-cart-widget.js
: This JavaScript file will handle the AJAX cart updates.jQuery(function ($) { // Update the cart widget function updateCartWidget() { $.ajax({ type: 'POST', url: wc_cart_widget_params.ajax_url, data: { action: 'woocommerce_cart_update', }, success: function (response) { var data = JSON.parse(response); $('.cart-count').html(data.cart_count); $('.cart-total').html(data.cart_total); }, }); } // Run the function on page load updateCartWidget(); // Hook into WooCommerce cart updates $(document.body).on('updated_cart_totals', function () { updateCartWidget(); }); });
This jQuery code is responsible for updating the cart widget in response to changes in the WooCommerce shopping cart. It sets up an AJAX call to retrieve the latest cart information from the server and then updates the cart widget on the page. 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.function updateCartWidget() { ... }
: This function is defined to perform the AJAX call and update the cart widget.- Inside the function, an AJAX request is initiated using
$.ajax
. type: 'POST'
: Specifies that it’s a POST request.url: wc_cart_widget_params.ajax_url
: The URL where the AJAX request is sent. The URL is taken from thewc_cart_widget_params
object, which is localized data passed from the server to the client-side script. It contains the AJAX URL.data: { action: 'woocommerce_cart_update' }
: The data sent with the request includes an ‘action’ parameter set to ‘woocommerce_cart_update’. This indicates the action to be performed on the server.success: function (response) { ... }
: A callback function that executes when the AJAX request is successful. It receives a ‘response’ parameter, which is typically a JSON-encoded string returned by the server.- Inside the success callback, the JSON response is parsed into a JavaScript object (
data
), and then the cart count and total are updated on the page using$('.cart-count').html(data.cart_count)
and$('.cart-total').html(data.cart_total)
.
- Inside the function, an AJAX request is initiated using
updateCartWidget();
: This line calls theupdateCartWidget
function when the page loads. This initial call ensures that the cart widget displays the correct information immediately.$(document.body).on('updated_cart_totals', function () { ... });
: This code hooks into the ‘updated_cart_totals’ event, which is triggered by WooCommerce when the cart totals are updated. It listens for this event on thedocument.body
.- When the ‘updated_cart_totals’ event occurs (typically after a cart update on the WooCommerce store), the
updateCartWidget
function is called again. This ensures that the cart widget is always up to date with the latest cart contents and totals.
- When the ‘updated_cart_totals’ event occurs (typically after a cart update on the WooCommerce store), the
In summary, this jQuery code sets up a function to update the cart widget by making an AJAX request to the server. It runs this function on page load and hooks into WooCommerce’s ‘updated_cart_totals’ event to keep the cart widget synchronized with changes to the shopping cart. This allows for a smooth and dynamic user experience when interacting with the cart on a WooCommerce-powered website.
css/woocommerce-cart-widget.css
: This CSS file will style the cart widget as needed.
/* Add your CSS styles here */
Step 3: Add the Widget to a Widget Area
Now that you’ve created the plugin and the necessary files, you can add the cart widget to a widget area.
- Go to your WordPress admin dashboard.
- Navigate to Appearance » Widgets.
- Find the “WooCommerce Cart” widget and drag it to your desired widget area (e.g., Sidebar, Footer).
- Customize the widget settings as needed, including the title.
Step 4: Activate the Plugin
Activate your custom WooCommerce Cart Widget plugin from the WordPress admin dashboard under the “Plugins” section.
That’s it! You’ve created a simple WooCommerce cart widget for your WordPress website using a custom plugin. The widget should now display in the specified widget area, and users can interact with it to view their cart contents and totals.