Supercharging WordPress by using HTMX Supercharging WordPress with HTMX (r)

Sep 20, 2024
WordPress and HTMX

-sidebar-toc>        -language-notice>

Although there are a variety of acceptable languages to code with, web development is settling into a few dependable technologies. This is particularly the case for WordPress.

JavaScript is still in the process of maturing its platform, even though the expectations of users for interactive and dynamic websites remain in high demand. Frameworks are able to bridge the gap, but the complexity of of the more popular ones can hinder your development. Enter HTMX. This lightweight library promises usability and ease of creating new web experiences for the modern age.

For this article we'll look at the ways that HTMX can integrate with your WordPress development workflow. Through this article, you'll discover how you can use this powerful and accessible way to build dynamic content and interaction.

We'll discuss the details of what HTMX is, how it's getting more attention, and how it connects with WordPress. In addition, you'll get a detailed tutorial on how to integrate and use HTMX with WordPress.

What exactly is HTMX?

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.
  • Asynchronous JavaScript and XML (AJAX). HTMX utilizes AJAX for executing 'async' requests towards the web server. It allows you to make small page updates without needing to reload the entire page.
  • WebSockets. You can establish WebSocket connections as well as enable real-time, bi-directional communication between the browser and the server.
  • Server-Sent Events (SSE). This technology allows the server to push data to the browser. In turn, you could utilize HTMX to make real-time page updates.
  • CSS Transitions. You can integrate with CSS Transitions that allow you to incorporate smooth and animated changes to your site.

We're discussing HTMX

There's been lots of buzz surrounding HTMX in recent times and searches for the library exploding in 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.
It's the Google Trends chart showing a growth in searches related to HTMX over the course of five years.

This popularity surge can be attributed to social media, as well as the forums for developers that are visible. Yet, HTMX has several factors which make it a desirable alternative for developers.

  • performance. By minimizing the amount of JavaScript needed, HTMX can deliver speedier loading times and superior performance over other frameworks, specifically on mobile devices.
  • Progressive enhancement. This means adding interactivity to websites without breaking functionality for those who disable JavaScript. HTMX is based on these principles, so there's an accessibility benefit to be had.

Furthermore, unlike some more complex frameworks HTMX doesn't require a complex construction process or toolchain. With a less steep process of learning, the integration of HTMX into your project is easier.

This, in turn result in a greater debate and increased use of HTMX. If you're looking for a more straightforward solution to creating interactive web experiences HTMX could be your ideal choice.

WordPress Architecture with respect to JavaScript

WordPress has a long history of JavaScript picked up pace at the State of the Word 2015 in which Matt Mullenweg ended with the line, "Learn JavaScript deeply."

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

There are pros and cons to using WordPress The present JavaScript implementation

This means there's a mix of frameworks and plugins which are compatible with WordPress' core code. There are some plus points and disadvantages of this. There are some positives to this:

  • The framework is widely used for React and JQuery. In the first case, it's an extremely popular and powerful framework. With the latter It has a long-standing association with WordPress.
  • A lot of developers are aware of the frameworks because React and jQuery are both popular. Additionally, you will get more information on how to master and troubleshoot both.
  • WordPress offers built-in support for AJAX via wp_ajax.

These pros do are not without a set of disadvantages to balance them out:

  • Utilizing the jQuery framework will boost your site's performance, and there's a chance that you don't need this framework for some applications.
  • Some of the "modern capabilities and features that are available in JavaScript are implemented into WordPress because of compatibility as well as security concerns. This could serve as an issue if you have something particular you'd like to develop.
  • In addition to React to areas of WordPress (such as the Block Editor and Site Editors) there is an additional learning curve than ever before.

WordPress is currently using a JavaScript design is suitable for you if you have the development knowledge of the recommended frameworks or are willing to study these frameworks. If not, you'll likely need a solution that does not have the complications of the typical frameworks yet still provides a modern interactive experience for users on the front. That's why HTMX should be a consideration.

The reason HTMX might be a better fit for certain WordPress projects

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've already discussed the various aspects involved However, let's summarize the main points:

  • The  weight of HTMX could have an enormous impact on performance when compared with React and jQuery.
  • The majority of WordPress developers consider themselves most knowledgeable in HTML and PHP rather than JavaScript. HTMX offers a much simpler means for entry into the world of working using it, similar to a markup language.
  • PHP and HTMX will also work well together, thanks to the rendering on the server side, which can again have a positive impact on the performance.
  • Although it is a newer library, it is possible to integrate HTMX with greater ease and be familiar in the way it operates. It will improve your workflow.

To aid in WordPress creation, we appreciate the speed with which you can prototype new functionality for a website. It is easy to build complex new features by coding within the already existing HTML. You are able to include React components, or even perhaps jQuery when needed.

Progressive enhancement is a key feature of HTMX that has appeal. Accessibility is an essential aspect of the design process as well. HTMX lets you create interactivity with no breaking users who decide to turn off JavaScript in the browser.

The  home page showing the My 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 home page showing the My dashboard.

With the high-quality performance of our hosting solutions A website that uses HTMX will be able to speed up. This will impact your ranking metrics in SEO, your traffic statistics in development, time to develop, troubleshooting workflow, and the entire development process.

Typical use cases typical use cases HTMX

It's mentioned in the last section, but HTMX will not be a framework you use as a direct replacement for any of the more familiar JavaScript frameworks. It will instead work best alongside what already exists in order to support the workload where necessary.

That means you'll be using HTMX for specific tasks the jQuery and React might not be the best choice for. Before you begin implementing HTMX within WordPress, let's give three typical scenarios in which HTMX can be used to improve WordPress.

Reloading of a partial page

One of the main reasons to use HTMX is the ability to make partial page refreshes happen with minimal fuss. This is a huge deal for many developers and designers, particularly when it comes to quick mockups as well as prototypes. However, HTMX can produce high-quality outputs.

It could, for instance, 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.
Live interactive search interface that is dynamically generated using HTMX.

The HTMX examples library also goes into the methodology for carrying out real-time updates for other content sections within the. In this case, their example uses a contact form with a table of available contacts that would refresh once users submit the latest addition. HTMX has a number of elegant ways to achieve this:

  Contacts
HTML0 Contacts HTML0 Contacts Contacts in HTML0 Contacts in HTML0 Name
Contact NameContacts Email
Contacts Name Email
Contacts Name EmailHTML5
  Contacts Name HTML0 EmailHTML5 ...
 Add A Contact ...
 Add Contact  Add a Contact 
 
HTML10 HTML11 Name
  
 
 Email
  

The form makes use of the HX-post and hx-target attributes to broaden the area of its focus. It is also possible to make use of HTMX attributes to keep the input fields of your form after an error or any other validation effort that utilizes refreshes:

 
 Submit Submit Submit
 
 Submit

This is where you insert the data of the binary file on top of the form element that is primary and use the HX-swap and hx-target attributes.

Dynamic loading

This method of dynamic refreshing and loading could also be suitable for more typical tasks. For instance, consider infinite scrolling as an example.     Agent Smith [email protectedAgent Smith [email protected]Agent Smith [email protected]55F49448C0 Agent Smith [email protected] 55F49448C0

The HX-swap attribute acts as a "listener" for the hx-trigger attribute. If a user gets to the bottom of the list, HTMX will open the following page of contacts on an infinite basis.

You could apply the identical method for lax loading functions, as well:

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.
Utilising HTMX for implementing Lazy Loading.

The same technique uses the hx-get and hx-trigger attributes to trigger an moving htmx to settle the graph with a gradual fade-in.

Data presentation

There is no need to be surprised that HTMX excels at displaying data on screens using active or other dynamic elements.

You can, for example, use all kinds of filtering for content including values selections. That's where the choices on one page are populated with the options 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.
Utilizing HTMX to assign value selections to web elements.

It is possible to set up modifiable dialogs or interface tabs with the same as ease. This also showcases how HTMX works alongside different frameworks and libraries 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 by using HTMX.

This flexibility extends to implementing tabs as well. There are two ways to do this using either a combination of vanilla JavaScript and HTMX or by 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 made using HTMX.

There are many methods to utilize HTMX to create front-end elements for your website with its core for server-side. In the following section we'll show you the tools to create your own vision within WordPress.

How can I incorporate HTMX in WordPress

If you want to add HTMX on your WordPress site, the great news is it's quick and pain-free. Next, we'll look at a three-step approach to complete the job. We won't cover the entire procedure and the code needed to create features that works with WordPress, although we will cover the most important points you need to follow.

Additionally, the majority of the procedure, particularly the very first stage, can be standard if you've already developed for WordPress.

1. In your PHP code

Similar to any other scripts for WordPress it is required to include the HTMX library within the code of your plugin or theme.

wp_enqueue_script('htmx-script', 'https://unpkg.com/[email protected]/dist/htmx.min.js', array(), '2.0.0', true);
 
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.
Be sure to use the most current version of HTMX Note that the guide to quick-start calls the library from a CDN that might not be suitable for your particular design.

2. Add HTMX elements to your WordPress template templates

hx-post
 

WordPress' AJAX requests use the admin-ajax.php endpoint, to be sure! Most of the components you create with HTMX create an AJAX request, and then forward it to the target element, and then possibly process a trigger.

The target attribute allows you to specify where your request will go. This might be on a separate page, or a certain div or anything else. Think of it like HTML anchor tags.

HTMX employs "natural" as well as "non-natural" to describe an action. As an example, submit will initiate a form, it's an event that occurs in the natural elements. For non-natural element events, it is recommended to use the HX-trigger attribute. Triggers could be among the more complicated components of HTMX however they're still very easy to understand.

You could, for instance, use a trigger to monitor an input field:

...
 hx-post="?action=live_search"
 hx-target="#search-results"
 hx-trigger="input changed delay:500ms, search"
 hx-indicator=".htmx-indicator">
 ...

Any change to an input field can trigger an update on another page. As another example one, it could be beneficial to start an event but only in response to a unique event, like a the cursor's entry into a specific area of the screen.


 [Here Mouse, Mouse!] 

3. Manage the AJAX requests

Finally, you need to take care of the AJAX request from the server side. For WordPress, it's a beneficial method to keep everything in separate files. You can call it what you'd like, however ajax-functions.php is descriptive and easy to read.

You'd probably do this anyway, regardless of whether or not you're programming with HTMX JavaScript, plain JavaScript or a different. Here's a pseudocode example to illustrate how this might look:

Function my_search_action() 
 $search_term = clean_text_field( $_POST['search"'['search'] ) and$args = array(
"s" is> $search_term,
 'post_type' => 'post',
 'posts_per_page' =more than 5) The query = the new WP_Query( $args ) in the event that ( the query is set to have posts() )  the following code will be executed:while ("$query->have_posts() ) : $query->the_post() andecho ' . get_the_title() . '';
 echo '' . get_the_excerpt() . "/p>'endwhile;
 else:
 echo 'No results discovered. ';
 endif;
 
 wp_reset_postdata();
 
 wp_die();
 

Strategies for using HTMX with WordPress

Although the use of HTMX is one of the easiest ways to create dynamic content in WordPress however, it requires careful management and consideration. There are a number of ways to improve the development experience.

The primary point is related to the'mature' of HTMX. Right now, it's an entirely new application for the platform, so it's not at the same level of integration as jQuery, for instance.

HTMX has great documentation, however there's a lack of options for combining it in conjunction with WordPress. That means you'll have do the work to make things run without the protection of a ready-made community.

As we're discussing the topic of WordPress take a look at the way that you can understand how admin-ajax.phpfile connects with other parts of the WordPress ecosystem, as many interactions will require 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 the code editor.
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 solicits for the WordPress.org website.

It's the repository of response and request data used to analyze AJAX requests as well as Application Programming Interface (API) calls. Given that HTMX does not yet provide a complete integration with WordPress and WordPress, debugging could be more relevant that it is with other JavaScript frameworks.

Summary

If you are WordPress developers that want to create dynamic, interactive site elements without complex JavaScript frameworks dominating your schedule, HTMX comes with an exciting brief. It lets you build within HTML and offers a slimline alternative to jQuery and React and still provides modern interactivity.

It is likely that you will use HTMX in conjunction with the other frameworks as it won't be suitable to all projects. It's still easy to set up and offers an easy way to test the interactive components of your website - which could eventually become your prototype version for production.

Do you think HTMX and WordPress appear like a captivating pairing to you? Tell us your thoughts by commenting below!

Jeremy Holcombe

Senior Editor at , WordPress Web Developer, and Content writer. Outside of everything WordPress I like playing golf, at the beach as well as movies. Also, I have height problems.