Skip to content

HTMX and WordPress: How I Combined Both Tools

HTMX and WordPress might not seem like a good match, especially when there’s a reliance on PHP and React in some places.

However, the lightweight JavaScript library lets you create dynamic, interactive web pages without the need for complex front-end frameworks. Whenever you require glitch-free functionality, HTMX could be the answer.

As such, I’ll show you how you can combine HTMX and WordPress. I’ll also have a plugin to give you, so you can see how the functionality works in a real setting!

HTMX and wordpress.

But first, maybe you’re wondering how is HTMX relevant for WordPress?

jQuery is falling behind. This leads most developers towards using React with WordPress. While it’s a better choice, it also suffers from performance problems in some cases. In general, frameworks will have greater bloat and complexity. Because HTMX is a library rather than a framework, it’s lean-compressed, and its file size is 14k.

In short, using HTMX could benefit performance while still providing the functionality you want. It can help create more dynamic and interactive experiences.

Some typical use cases

HTMX will be suitable wherever you use a JavaScript framework already. In its most basic form, you could create dynamic content updates without the need for page refreshes. If you have to display real-time data, such as live polls, stocks, or weather, this will be invaluable.

A front end form displaying dynamic content using HTMX.

This dynamic functionality also extends to other site elements, such as forms. For multistep forms or those that rely on real-time validation, this can boost the user experience (UX).

HTMX will also let you take care of some typical JavaScript tasks:

  • You’re capable of implementing lazy loading and infinite scrolling functionalities.
  • If you are looking for modal or pop-up windows, HTMX can help.
  • You can add microinteractions, such as progress bars, loading spinners, and other interactive elements. This is where HTMX’s event and response handling shines.
  • Even your navigation menu can benefit, as you can leverage the partial page reloads to expand and collapse your menus.

However, HTMX can tackle larger and more complex tasks too. For instance, you can combine HTMX with SSE or WebSockets to add real-time notifications or updates for user events. You also have the ability to implement inline editing and drag-and-drop interfaces.

How to use HTMX and WordPress together (a 3-step guide)

Another use case is adding live search and filtering functionality. This time, you’re coming along for the ride!

The tool will let the user enter a search query, then display a list of results – site pages in this case. This will be without full page reloads and with no need to ‘confirm’ the search in browser.

👉 Before starting, let’s discuss your freebie!

The companion plugin to this tutorial

If you want to follow along, I have a rough example plugin that showcases HTMX’s functionality in the form of an active search Block. You can download it from GitLab, although I recommend you don’t use it on a live site for a couple of reasons:

  • First, there is little security in the plugin. This is so I can show off the functionality in a clear way. For example, you’ll notice the plugin doesn’t include nonces for brevity’s sake, which is not something you want to deal with on a live site.
  • Second, the plugin calls HTMX from a CDN, which isn’t ideal for production sites. Again, this is the most straightforward (and default) way to enqueue HTMX and makes showcasing the functionality easier.

Of course, there is also no support provision for this plugin – it’s purely a proof-of-concept example, so using it is entirely at your own risk.

1. Enqueue the library within your PHP code

The first step for any inclusion is to enqueue the library within your WordPress theme or plugin:

wp_enqueue_script('htmx-script', 'https://unpkg.com/htmx.org@1.9.11/dist/htmx.min.js', array(), '1.9.11', true);

This is a typical way to enqueue scripts, and in this case, the library comes from a CDN. Note that you’ll want to use the latest version of HTMX – the home page will show the version number in its quick start script:

The HTMX quick start script showing the version number in the URL.

2. Add your HTMX to a WordPress template file

In its simplest form, HTMX relies on two elements: the correct attributes in your markup to handle AJAX requests, and the triggers for them. In fact, AJAX is the key.

You first need to add attributes to your HTML that let you issue AJAX requests. These have parity to typical HTTP requests. For instance, you can use GET, POST, PUT, PATCH, and DELETE. Regardless of the attribute you choose, you can spot HTMX markup through the hx- prefix:

hx-post="<?php echo admin_url('admin-ajax.php'); ?>…

Adding the hx-post attribute to your main plugin file or theme’s functions.php file tells your code to issue a POST request to the specified URL. Here, it’s the WordPress admin-ajax.php file.

However, you also need a target for the results: hx-target lets you specify another element than the one issuing the AJAX request. For us, we want to format the results on the page, so I’ll target a div:

<input type="search"
    name="search" placeholder="Search...">
    hx-post="<?php echo admin_url('admin-ajax.php'); ?>?action=live_search"
    hx-target="#search-results">

…Code language: HTML, XML (xml)

Elsewhere in the code, I create a blank div and give it the target as an ID – much like HTML anchors. From here, you also need to process the request and display the results.

3. Handle the AJAX request and display the results

To display the results of the action, I recommend you create a new file for processing your AJAX requests. This will keep your code neat and tidy.

Of course, what the file contains will depend on your desired outcome. For this live search example, you can see the final code in the companion plugin’s ajax-functions.php file.

It’s a simple PHP script that uses WP-Query to grab page and post titles, then list them along with a permalink:

A HTMX form on the front end of a WordPress website.

Within that plugin, you’ll also spot a JavaScript file that registers the functionality as a Block. It makes the active search a reusable and flexible element, without the bloat of a framework!

How to best use HTMX and WordPress together

For experienced coders, adding HTMX to WordPress shouldn’t be too much of a stretch to achieve. After some time using them, I have a few tips to pass along:

  • Bear in mind WordPress’ customs when it comes to enqueueing scripts, fetching URLs, and other tasks. Sometimes you have to work around WordPress to implement HTMX in the right way.
  • A plugin is probably the best way to integrate the two. You wouldn’t want to hard code this into your site at the minute, so give yourself the option to toggle your HTMX on and off.
  • Lean on your browser’s DevTools, such as the Console and Network tabs. Looking for XHR requests will be a constant task on your to-do list.
  • Remember that WordPress’s AJAX requests go through the admin-ajax.php endpoint. In fact, this is one big change between the example HTMX projects and WordPress. This will need a mixture of PHP alongside your HTML, and for you to specify the correct function within your AJAX file as part of the URL.

Finally, the documentation for HTMX is excellent, but there is hardly any progress when it comes to using it with WordPress. This means you’ll need to put in some legwork when it comes to troubleshooting.

Final words

I think combining the two is a fantastic way to develop dynamic and interactive experiences without the need for a framework. Using HTMX simplifies the process of adding AJAX-powered functionality to WordPress. In some cases, you may not even need code JavaScript to realize your vision.

Using HTMX is straightforward too: add attributes to your HTML, enqueue your scripts, and process the output.

Despite the simple entry point, HTMX has lots of scope to deliver everything other frameworks (such as jQuery, React, and Vue) can.

Did you try using this combination? Share your experience in the comments section below!

Don’t forget to join our crash course on speeding up your WordPress site. Learn more below:

 
Yay! 🎉 You made it to the end of the article!
Tom Rankin
Share:

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Sameer Hassan
April 3, 2024 7:50 am

I created my own child theme for elementor with htmx work like react

Or start the conversation in our Facebook group for WordPress professionals. Find answers, share tips, and get help from other WordPress experts. Join now (it’s free)!

1
0
Would love your thoughts, please comment.x