While there are many acceptable languages to code with, web development is settling into a few dependable technologies. This is especially true for WordPress.

JavaScript is still maturing for the platform, although user expectations for dynamic and interactive websites are still in demand. Frameworks can bridge that gap, but the complexity of some of the more popular ones can hinder your development. Enter HTMX. This lightweight library promises to deliver usability and simplification when creating modern web experiences.

For this article, we’ll explore how HTMX can integrate into your own WordPress development workflow. Throughout, you’ll learn how to use this powerful and accessible way to build dynamic content and interactivity.

We’ll discuss what HTMX is, why it’s gaining traction, and how it connects with WordPress. You’ll also get a practical guide on integrating and using HTMX with WordPress.

What HTMX is

The HTMX logo, which consists of the text "htmx" in white letters, with angle brackets on either side representing HTML tags. The "x" in "htmx" is colored blue for emphasis. Below the main text is a tagline that reads "high power tools for HTML". The logo is set against a dark background, creating a striking contrast.
The HTMX logo.

In a nutshell, HTMX is a JavaScript library that extends the standard HyperText Markup Language (HTML) without the need to write vanilla or framework JavaScript. These extensions let you access other technologies, too:

  • Asynchronous JavaScript and XML (AJAX). HTMX uses AJAX to carry out ‘async’ requests to the server. This lets you make partial page updates without needing a full page reload.
  • WebSockets. You can establish WebSocket connections and enable real-time, bi-directional communication between the browser and the server.
  • Server-Sent Events (SSE). This technology lets the server push data to the browser. From there, you can use HTMX to make real-time page updates.
  • CSS Transitions. You can integrate with CSS transitions, which lets you implement smooth and animated updates to your site.

At its core, HTMX looks to simplify how you create dynamic, interactive web apps. Its key functionality is how it can make GET, POST, PUT, PATCH, and DELETE HTTP requests from HTML elements. This means you can process slick and smooth partial page updates like a mobile app. On the whole, HTMX is a powerful toolkit to help you create a dynamic web experience without the need for reams of JavaScript code.

Why we’re all talking about HTMX

There’s been a buzz around HTMX recently, with searches for the library exploding over the past five years.

A line graph showing interest over time from July 2019 to January 2024. The graph starts low and relatively flat until mid-2022, then shows a sharp increase followed by fluctuations at a higher level through 2023 and into early 2024.
The Google Trends chart showing a rise in searches for HTMX over a five-year period.

This popularity surge is in part due to social media and developer forum visibility. However, HTMX has several factors that make it an attractive development option.

  • Simplicity. Because HTMX uses familiar HTML syntax to help you create dynamic, interactive web apps, it’s super simple to implement and comes with almost none of the complexity of typical JavaScript frameworks.
  • Performance. By minimizing the amount of JavaScript needed, HTMX can deliver faster load times and better performance than other frameworks, especially for mobile devices.
  • Server-side rendering. Server-side rendering is great if you want to improve initial page load times and Search Engine Optimization (SEO). HTMX incorporates this into its feature set.
  • Progressive enhancement. This means adding interactivity to websites without breaking functionality for those who disable JavaScript. HTMX works on these principles, so there’s an accessibility benefit on hand.

Furthermore, unlike some larger frameworks, HTMX doesn’t require a complex build process or toolchain. Combined with a much shallower learning curve, integrating the library into your projects is easier.

These benefits, in turn, lead to greater discussion and adoption of HTMX. If you’re looking for a more straightforward solution to creating interactive web experiences, this library could be your choice.

WordPress’ architecture in relation to JavaScript

WordPress’ history with JavaScript gathered pace from the State of the Word 2015 when Matt Mullenweg closed with the line, “Learn JavaScript deeply.”

The typical pathway for WordPress developers was to research the need for interactive and dynamic components on a website. In most cases, jQuery has been the WordPress go-to JavaScript framework. Even the uber-popular Harvard Gazette website builds on top of jQuery:

The Harvard Gazette home page, showing a large hero image of an older woman, and a sidebar of current news articles, complete with featured images.
The Harvard Gazette website, which uses WordPress and jQuery to run.

As such, WordPress enqueues jQuery by default. In addition, lots of core features, plugins, and themes have extensive usage. This approach is consistent and has wide support.

The WordPress Block Editor interface. On the left side is a sidebar with various Block options such as Paragraph, Heading, List, and Table. The main content area shows a Table Block with version numbers and release dates for WordPress, along with options to upload media or access the media library. The interface has a clean, modern design with a white background.
Showing the Blocks sidebar within the WordPress Block Editor.

However, as web development evolves, so does WordPress’ approach to JavaScript. The introduction of the Block Editor came with a shift towards using the React framework for building user interfaces, especially within the WordPress dashboard.

The pros and cons of using WordPress’ current JavaScript implementation

This means there’s a mix of frameworks with support in WordPress’ core code. There are some plus points and drawbacks to this. First, the positives:

  • There’s widespread compatibility for both React and jQuery. For the former, it’s a powerful and popular framework. With the latter, it has a long-standing association with WordPress.
  • Many developers are familiar with the frameworks because React and jQuery are popular. What’s more, you can find more resources to learn and troubleshoot both.
  • WordPress offers built-in support for AJAX through wp_ajax.

However, these pros have a batch of negatives to balance them out:

  • Relying on jQuery offers a hit to your site’s performance, and you may not need the framework at all for some applications.
  • Not all of the ‘modern’ features and functionality of JavaScript are implemented within WordPress due to compatibility and security reasons. This could serve as a problem if there’s something particular you’d like to build.
  • With the addition of React to areas of WordPress (such as the Block and Site Editors), you have an even greater learning curve than ever before.

WordPress’ current JavaScript architecture is suitable if you have the development knowledge of the recommended frameworks or the time to learn them. If not, you’ll likely want a solution that doesn’t come with the complexity of the typical frameworks yet still provides a modern interactive experience on the front end. This is where HTMX should be a consideration.

Why HTMX could be a better fit for some WordPress development tasks

HTMX offers a few compelling advantages when it comes to WordPress development. It could provide a middle ground between jQuery’s simplicity and the modern, performant React.

We already talk about some of these aspects, but let’s recap them in brief:

  • The ‘weight’ of HTMX can have a big impact on performance compared to jQuery and React.
  • Most WordPress developers consider themselves most knowledgeable in HTML and PHP rather than JavaScript. HTMX presents an easier barrier of entry as you work with it, much like a markup language.
  • PHP and HTMX will also work well together, thanks to the server-side rendering, which could again have a positive impact on performance.
  • Despite being a ‘newer’ library, you can integrate HTMX with greater ease and get up to speed with how it works. This will benefit your workflow.

For WordPress development, we also like the ease with which you can prototype new functionality for a site. You can quickly build out complex new features by coding within the existing HTML. From there, you have the flexibility to add in React components or a little jQuery where necessary.

HTMX’s progressive enhancement principles also appeal. Accessibility should be central to your design strategy, and HTMX can let you build interactivity without breaking it for those who choose to disable JavaScript in the browser.

Finally, one significant advantage of HTMX is that it doesn’t require any custom or special server-side setup. You can use your HTMX markup with any host – including Kinsta.

The Kinsta home page showing the MyKinsta dashboard. It includes basic details such as location (Belgium) and site name, environment details with IP addresses, SFTP/SSH connection information, and two graphs. One graph shows site visits over time, and the other shows overall transaction time broken down by technology components.
The Kinsta home page showing the MyKinsta dashboard.

Given the quality performance of our hosting provisions, a site using HTMX should blaze along. This will impact your SEO metrics, traffic numbers, development time, troubleshooting workflow, and the whole development chain.

Typical use cases for HTMX

We tease it in the last section, but HTMX won’t be a library you use as a direct replacement for any of the more familiar JavaScript frameworks. Instead, it will work best alongside what already exists to help carry the load where necessary.

This means you’ll employ HTMX for certain tasks that jQuery and React may not be optimal for. Before diving into implementing HTMX in WordPress, let’s give three common scenarios where the library could enhance WordPress.

Partial page reloads

The big use case for HTMX is how you can implement partial page refreshes with minimal fuss. This could be a big deal for many developers, especially for quick mockups and prototypes. However, HTMX could deliver production-quality results.

For instance, it could help you implement live search functionality on your site:

A GIF of a dynamic search dialog using HTMX with a dark background. It displays a table of contacts, showing first names, last names, and email addresses for multiple individuals. The table includes 10 rows of sample contact information.
A live, dynamic search interface using HTMX.

The HTMX example library also goes into the methodology for carrying out real-time updates on other content areas within the page. For instance, their example uses a contact form with a table of available contacts that would refresh once a user submits a new addition. HTMX has a number of elegant ways to achieve this:

<div id="table-and-form">
    <h2>Contacts</h2>
    <table class="table">
      <thead>
        <tr>
          <th>Name</th>
          <th>Email</th>
          <th></th>
        </tr>
      </thead>
      <tbody id="contacts-table">

        ...

      </tbody>
    </table>

    <h2>Add A Contact</h2>

    <form hx-post="/contacts" hx-target="#table-and-form">
      <label>
        Name
            <input name="name" type="text">  
      </label>

      <label>
        Email
            <input name="email" type="email">  
      </label>
    </form>
</div>

The form uses the hx-post and hx-target attributes to expand its target. You could also use HTMX attributes to preserve form input entries after an error or other validation attempt that uses refreshes:

<input form="binaryForm" type="file" name="binaryFile">

<form method="POST" id="binaryForm" enctype="multipart/form-data" hx-swap="outerHTML" hx-target="#binaryForm">
    <button type="submit">Submit</button>
</form>

Here, you place the input for the binary file outside of the primary form element and use the hx-swap and hx-target attributes.

Dynamic loading

This approach to dynamic refreshing and loading can also be suitable for more common tasks. Take infinite scrolling, for example:

<tr hx-get="/contacts/?page=2"
    hx-trigger="revealed"
    hx-swap="afterend">
  <td>Agent Smith</td>
  <td>[email protected]</td>
  <td>55F49448C0</td>
</tr>

The hx-swap attribute acts as a ‘listener’ for the hx-trigger attribute. Once a user reaches the end of the list, HTMX will load in the second page of contacts on an infinite basis.

You could apply the same method to lazy loading functionality, too:

A GIF of a dark-background web page, which implements lazy loading. The GIF begins with a small loading animation, from which a graph image fades in as the user scrolls down the page.
Using HTMX to implement Lazy Loading.

This again uses the hx-get and hx-trigger attributes to start a htmx-settling transition to load the graph using a slow fade-in.

Data presentation

It should be no surprise that HTMX is excellent for presenting information on screen using interactive or otherwise dynamic elements.

For instance, you can implement all content filtering types, such as value selections. This is where the options in one list populate based on those of another:

A GIF of a ​user interface showing a drop-down menu for selecting a car make and model. The title says "Pick A Make/Model" and the options visible are Audi (which is selected), Toyota, and BMW. The user cycles through each Make, which changes the options in the Model drop-down menu.
Using HTMX to assign value selections to site elements.

You could even set up modal dialogs or interface tabs with just as much ease. This also showcases how HTMX works alongside other libraries and frameworks, such as Bootstrap:

A GIF of a light-themed web page section titled "Demo" with a link icon and a button titled "OPEN MODAL" in capital letters. Once the user clicks the button, this opens a modal box using HTMX.
Opening a modal dialog box using HTMX.

This flexibility extends to implementing tabs, too. There are two ways to do this: either through combining vanilla JavaScript and HTMX or using Hypertext As The Engine Of Application State (HATEOAS) principles:

A GIF of a HTMX tabbed interface with three tabs labeled "Tab 1", "Tab 2", and "Tab 3". The user flicks between each tab, which displays different paragraphs of placeholder ‘Lorem Ipsum’ text. The interface has a dark background with white text, giving it a sleek, modern appearance.
A GIF of a tabbed interface using HTMX.

There are plenty more ways to use HTMX for front-end site elements with its core on the server side. In the next section, we’ll give you the tools to create your own vision within WordPress.

How to integrate HTMX into WordPress

If you want to add HTMX to your WordPress website, the good news is it’s quick and pain-free. Next, we’ll look at a three-step approach for the job. We won’t cover the entire process and code to develop functionality for WordPress, although we will hit all the key points you need to follow.

Moreover, much of the process, especially the first step, should be typical if you have already developed for WordPress.

1. Enqueue HTMX within your PHP code

As with any additional scripts for WordPress, you must include the HTMX library in your theme or plugin’s code.

wp_enqueue_script('htmx-script', 'https://unpkg.com/[email protected]/dist/htmx.min.js', array(), '2.0.0', true);

Note: The HTMX quick start guide calls the library from a Content Delivery Network (CDN). You should decide whether this is a good idea for your project.

A code snippet from the HTMX quick start guide. It displays a single line of HTML code that includes a script tag to load the HTMX library from an external source. The code is highlighted in orange to draw attention to it. Below the script tag is an example of an HTML button element using HTMX attributes. The code is displayed on a dark background with syntax highlighting.
Make sure you use the latest version of HTMX, and note that the quick start guide calls the library from a CDN – which may not suit your project.

However, an objectively good idea is to wrap this enqueue within a function that also enqueues and registers a Block within WordPress. Of course, this depends on whether your project requires you to work with the Block Editor.

The final part for enqueuing HTMX is to invoke the entire function using add_action. You’ll need to come back to using hooks and filters later on when working with AJAX requests.

2. Add HTMX elements to your WordPress template files

From our use cases, you’ll see that HTMX requires the appropriate markup within the HTML to handle and trigger AJAX requests. The library uses typical HTTP request attributes to make up its own – GET, POST, PUSH, PATCH, and DELETE – with a hx- prefix:

hx-post

WordPress’ AJAX requests use the admin-ajax.php endpoint, which you should remember! The typical elements you’ll create with HTMX will make an AJAX request, send it to a target element, and potentially process a trigger.

The hx-target attribute lets you specify where the result of your request will go. This could be another page, a specific div, or something else. Think of it like HTML anchor tags:

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

HTMX uses “natural” and “non-natural” to define an action. For instance, submit will trigger a form, and this is a natural element event. For non-natural element events, you’ll use the hx-trigger attribute. These triggers can be one of the more complex parts of HTMX, yet still simple to understand.

For example, you could use a trigger to monitor an input field:

…
hx-post="<?php echo admin_url('admin-ajax.php'); ?>?action=live_search"
hx-target="#search-results"
hx-trigger="input changed delay:500ms, search"
hx-indicator=".htmx-indicator">
…

Changing whatever is in an input field will trigger an update elsewhere on the page. As another example, you might want to trigger an event one time only based on a non-typical action, such as cursor entry into a portion of the screen:

<div hx-post="/mouse_entered" hx-trigger="mouseenter once">
    [Here Mouse, Mouse!]
</div>

This might inspire you to create applications such as pop-ups or other modal boxes. However, before you can see these in action, you have to process the AJAX request.

3. Handle the AJAX requests

Finally, you need to handle the AJAX request on the server side. For WordPress, it’s a beneficial practice to store all of this in a separate file. You can call it what you like, but ajax-functions.php is descriptive and clear enough.

This part of using HTMX will require you to break out your PHP skills. Processing your AJAX requests will be unique to your particular project. It’s where you link the attributes you name in your template files to server-side processing.

Of course, you’d do this anyway, regardless of whether you code with HTMX, vanilla JavaScript, or something else. Here’s some pseudocode to show how this might look:

function my_search_action() {
    $search_term = sanitize_text_field( $_POST['search'] );

    $args = array(
        's' => $search_term,
        'post_type' => 'post',
        'posts_per_page' => 5
    );

    $query = new WP_Query( $args );

    if ( $query->have_posts() ) :
        while ( $query->have_posts() ) : $query->the_post();
            echo '<h2>' . get_the_title() . '</h2>';
            echo '<p>' . get_the_excerpt() . '</p>';
        endwhile;
    else:
        echo 'No results found.';
    endif;

    wp_reset_postdata();

    wp_die();
}

Even so, this might not be relevant or even look like your own project’s AJAX handling. The same skills you’ll use for building Block templates, extending plugins using PHP, and more will help you make your own AJAX request handlers and functions.

Tips for using HTMX with WordPress

While using HTMX is one of the simplest ways to implement dynamic content with WordPress, it still needs careful management and consideration. There are also a few ways to improve your development experience.

The first tip relates to HTMX’s ‘maturity’. Right now, it’s a new library for the platform, so it doesn’t have the same level of integration as jQuery, for instance.

HTMX has great documentation, but there aren’t as many resources for combining the library with WordPress. This means you’ll need to put in the legwork to make things run without the safety net of a ready-made community.

One of the big pieces of advice we can pass along is to build your functionality into a plugin for now. This can give you structure and easier management while you check for bugs and other integration errors.

While we’re on the subject of WordPress, look to understand how the admin-ajax.php file connects with the rest of the ecosystem, as many interactions will involve it.

A code editor window displaying PHP code for a WordPress admin-ajax.php file. The code includes comments and functions for loading WordPress bootstrap code, handling cross-domain requests, setting headers, and loading WordPress administration APIs and Ajax handlers. The editor has a dark theme with light blue syntax highlighting.
The admin-ajax.php file within a code editor.

Although HTMX has great performance, you should ensure AJAX usage is low enough to not impact your site’s loading speeds or SEO. Debugging requests should also be a staple of your workflow, especially the XMLHttpRequest (XHR) metrics within your browser’s developer tools.

The Brave browser’s DevTools interface, showing the WordPress website at the top. This includes text describing it as "The open source publishing platform of choice for millions of websites worldwide" and a video thumbnail about WordCamp Europe 2024. The developer console shows XHR requests for the site.
The Fetch/XHR requests for the WordPress.org website.

This is the record of request and response data, which you’ll use to debug AJAX requests and Application Programming Interface (API) calls. Given that HTMX doesn’t yet have tight integration with WordPress, debugging might be a more pertinent task than it would be with other JavaScript frameworks.

Summary

For WordPress developers who want to create dynamic, interactive site elements without complex JavaScript frameworks dominating your time, HTMX comes with an exciting brief. It lets you build within HTML and offers a slimline alternative to jQuery and React while still giving you modern interactivity.

In practice, you’ll use HTMX alongside those other frameworks, as it won’t be suitable for all tasks. Even so, it’s simple to implement and gives you a rapid way to prototype your site’s interactive elements – and could even become your production version.

Does HTMX and WordPress look like a tantalizing pairing to you? Let us know your thoughts in the comments section below!

Jeremy Holcombe Kinsta

Content & Marketing Editor at Kinsta, WordPress Web Developer, and Content Writer. Outside of all things WordPress, I enjoy the beach, golf, and movies. I also have tall people problems ;).