Using HTMX with WordPress to Enhance Platform Functionality Without Complex Frameworks

While there are many options for turning into a language, each language is suitable for its own application scenario, and as technology evolves, web development is evolving into several reliable techniques. This is especially true for WordPress.

While user expectations for dynamic and interactive websites remain high, JavaScript is still maturing on the platform. Frameworks can bridge this gap, but the complexity of some of the more popular frameworks may hinder your development.HTMXThis lightweight library promises usability and simplicity in creating modern web experiences.

In this article, we'll explore how to integrate HTMX into our own WordPress development workflow. Throughout, we'll learn how to build dynamic content and interactivity using this powerful and easy-to-use approach.

We'll discuss what HTMX is, why it's growing in popularity, and how it integrates with WordPress. You'll also get a practical guide to integrating and using HTMX with WordPress.

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

In a nutshell.HTMXis a JavaScript library that extends the standard Hypertext Markup Language (HTML) without the need to write native or framed JavaScript.With these extensions, we can also use other technologies:

  • Asynchronous JavaScript and XML (AJAX).HTMX uses AJAX to send “asynchronous“ requests to the server. This allows you to update parts of the page directly without having to reload the entire page.
  • WebSockets You can establish a WebSocket connection to enable real-time two-way communication between the browser and the server.
  • Server Send Event (SSE).This technology allows the server to push data to the browser. From there, you can use HTMX for live page updates.
  • CSS Transition.You can integrateCSS Transitiontechnology, resulting in smooth animated updates on the site.

At its core, HTMX is designed to simplify the process of creating dynamic, interactive Web applications. The key feature is how to emitGET,POST,PUT,PATCH respond in singingDELETE HTTP requests. This means that we can handle partial page updates as smoothly as we do mobile applications. Overall, HTMX is a powerful toolkit that helps us create dynamic web experiences without having to write tons of JavaScript code.

Why we're all talking about HTMX

HTMX has been generating a lot of buzz lately in theOver the past five years, searches for this library have exploded.

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.
Google Trends shows that searches for htmx have been trending upwards over the past five years.

This surge in popularity can be attributed in part to HTMX's visibility on social media and developer forums.Several factors make HTMX an attractive development option.

  • Simple.Because HTMX uses familiar HTML syntax to help us create dynamic, interactive web applications, it is simple to implement without the complexity of typical JavaScript frameworks.
  • Performance.HTMX minimizes the amount of JavaScript used, so theFaster loading times, performance is better than other frameworks, especially on mobile devices.
  • Server-side rendering.Server-side rendering is a good choice if you want to improve initial page load times and search engine optimization (SEO), which HTMX incorporates into its feature set.
  • Gradual enhancement.This means adding interactivity to the site without breaking functionality for users who have JavaScript disabled. HTMX follows these principles and therefore has accessibility advantages.

Additionally, unlike some large frameworks, HTMX does not require a complex build process or toolchain. Coupled with a much shallower learning curve, integrating the library into our projects was much easier.

These benefits have in turn fueled developer discussion and adoption of HTMX. If you're looking for a more straightforward solution to creating interactive web experiences, this library may be for you.

WordPress vs JavaScript

WordPress' history with JavaScript began with2015State of the Word 2015“, when Matt Mullenweg closed with a “deep dive into JavaScript“.

The typical path for a WordPress developer is to research the site's need for interactive, dynamic components. For the most part, jQuery has been the JavaScript framework of choice for WordPress. Even the popular Harvard Gazette website is built on 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 is running on WordPress and jQuery!

As a result, WordPress integrates with jQuery by default. in addition, many core features, plugins, and themes make extensive use of jQuery. this approach is consistent and widely supported.

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.
Display the block sidebar within the WordPress block editor.

However, as web development has evolved, so has WordPress' approach to JavaScript. With the introduction of the block editor, the approach to building user interfaces began to shift in the direction of thinking about using the React framework, especially within the WordPress dashboard.

Advantages and disadvantages of using WordPress' current JavaScript implementation

This means supporting multiple frameworks in the core WordPress code. There are both advantages and disadvantages to this. First the pros:

  • React and jQuery have a wide range of compatibility. The former is a powerful and popular framework. For the latter, it has a long association with WordPress.
  • Due to the popularity of React and jQuery, many developers are familiar with both frameworks. What's more, we can find more resources to learn and troubleshoot both frameworks.
  • WordPress via wp_ajax Built-in support for AJAX.

However, these advantages come with some disadvantages:

  • Dependency on jQueryIt will affect the performance of the site, and some applications may not need the framework at all.
  • For compatibility and security reasons, WordPress does not implement all the “modern“ features and functionality of JavaScript. This can be a problem if you want to build some special features.
  • With the addition of React to various areas of WordPress (such as the block and site editors), we're going to have a harder time learning than ever before.

If you have development knowledge of the recommended frameworks or the time to learn them, WordPress' current JavaScript architecture is appropriate. If not, you may need a solution that doesn't have the complexity of typical frameworks while still providing a modern interactive experience on the front end. This is where HTMX needs to be considered.

Why HTMX is better suited for certain WordPress development tasks

HTMX has some compelling advantages when it comes to WordPress development. It provides a middle ground between the simplicity of jQuery and the modern, high performance of React.

We have already discussed some of these aspects, so let us briefly review them below:

  • The “weight“ of HTMX can have a big impact on performance compared to jQuery and React.
  • Most WordPress developers consider themselves most familiar with HTML and PHP rather than JavaScript. HTMX is like a markup language that is much easier to get used to.
  • PHP and HTMX also work well together thanks to server-side rendering, which also has a positive impact on performance.
  • Even though HTMX is a “newer“ library, you can integrate HTMX more easily and get a handle on how it works. This will benefit your workflow.

For WordPress developers, we also love how easy it is to prototype new features for your website. You can quickly create complex new features within existing HTML code. On top of that, you have the flexibility to add React components or a little jQuery as needed.

HTMX's principle of incremental enhancements is also appealing. Accessibility should be at the center of your design strategy, and HTMX allows you to build interactivity without breaking it for users who choose to disable JavaScript in their browsers.

Finally, a significant advantage of HTMX is that it doesn't require any customization or special server-side setup. You can use HTMX on any host.

Typical use cases of HTMX

As we previewed in the previous section, HTMX will not be a library you use as a direct replacement for any of the more familiar JavaScript frameworks. Instead, it will work best alongside existing frameworks to help carry the load when necessary.

This means you'll be using HTMX to accomplish certain tasks that jQuery and React may not be able to do. Before we dive into how to implement HTMX in WordPress, let's cover three common scenarios where the library can enhance WordPress.

Partial page reloading

The main use case for HTMX is how to implement partial page reloading with minimal effort. This can be a big problem for many developers, especially for rapid mockups and prototypes. However, HTMX can deliver production quality results.

For example, it can help you to implement a real-time search function on your website:

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.
Use HTMX's real-time dynamic search interface.

HTMXsample library (computing)Methods for real-time updates in other content areas within the page were also presented. For example, their example uses a contact form with a table of available contacts that refreshes as soon as the user submits a new contact.HTMX has a number of elegant ways to accomplish 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" action="">
      <label>
        Name
            <input name="name" type="text">  
      </label>

      <label>
        Email
            <input name="email" type="email">  
      </label>
    <input type="hidden" name="trp-form-language" value="en"/></form>
</div>

The form uses thehx-postrespond in singinghx-targetattribute to extend its target. You can also use the HTMX attribute after errors or other validation attempts using the RefreshRetain form input entries::


</form

Here, we place the binaryForm input outside of the main form element and use thehx-swaprespond in singinghx-targetProperties.

dynamic loading (computing)

This dynamic refresh and load approach also applies to more common tasks. TakeInfinite scrollingAs an example:


  Agent Smith</td
  amos@example.com</td
  55F49448C0

hx-swapAttributes acting ashx-triggerattribute of the “listener”. Once the user reaches the end of the list, HTMX loads the second page of contact information indefinitely.

You can also apply the same method to thelazy loading (computing)Function:

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.
Lazy loading is implemented using HTMX.

This will again use thehx-getrespond in singinghx-triggerattribute starts the htmx-settling transition to load the chart using a slow fade.

Data Display

It's no surprise that HTMX is a great tool for presenting information on screen using interactive or other dynamic elements.

For example, you can implement all content filter types, theas selected by value. In this case, the options in one list are populated based on the options in the other list:

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.
Use HTMX to assign value selections to site elements.

You can even easily setModal dialog boxor interface tabs. This also shows how HTMX works with 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.
Use HTMX to open the mode dialog.

This flexibility extends to the implementation of labels as well. There are two ways to do this: one is to combine theGeneral JavaScriptand HTMX, the other usingHypertext as an Application State Engine (HATEOAS)Principle:

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.
GIFs using HTMX's tagging interface.

There are also many ways to use HTMX for front-end website elements that have their core on the server side. In the next section, we'll give you the tools to create your own vision in WordPress.

How to Integrate HTMX into WordPress

If you want to add HTMX to your WordPress site, the good news is that it's quick and easy. Next, we'll go over the three steps of this endeavor. We won't cover the entire process and code for developing features for WordPress, but we will cover all the key points you need to follow.

Also, if you've developed for WordPress, most of the process, especially the first steps, should be pretty typical.

1. Enabling HTMX in PHP code

As with other scripts in WordPress, you must include the HTMX library in the code of your theme or plugin.

wp_enqueue_script('htmx-script', 'https://unpkg.com/htmx.org@2.0.0', 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.

Make sure to use the latest version of HTMX and note that the quick start guide is from the CDN enqueue library, which may not be appropriate for your project. However, a good idea would be to encapsulate this enqueue in a function that also enqueues and registers a block in WordPress. Of course, this depends on whether your project requires the use of a block editor.

The final part of introducing HTMX is to use theadd_actionCall the entire function. You will need to use the hooks and filters again later when processing AJAX requests.

2. Add the HTMX element to the WordPress template file.

From our use case, you'll see that HTMX requires appropriate markup in the HTML to handle and trigger AJAX requests. The library uses typical HTTP request attributes (GET,POST,PUSH,PATCH respond in singingDELETE), and tohx-as a prefix:

hx-post

Using AJAX Requests in WordPress admin-ajax.php endpoints, you should keep this in mind! A typical element created with HTMX makes an AJAX request, sends it to the target element, and possibly handles triggers.

pass (a bill or inspection etc)hx-targetattribute, you can specify where the result of the request goes. This could be another page, a specificdiv or other content. Think of it as an HTML anchor tag:

<input type="search"
        name="search" placeholder="Search..."
        hx-post="?action=live_search"
        hx-target="#search-results"
        ...

HTMX uses “natural“ and “unnatural“ to define operations. For example.submit (a report etc)will trigger a form, which is a natural element event. For non-natural element events, thehx-triggerProperties.These triggersProbably one of the more complex parts of HTMX, but still simple to understand.

For example, you can use triggers to monitor input fields:

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

Changing anything in an input field triggers an update elsewhere on the page. Then again, you might want to trigger an event all at once based on an atypical action, such as the cursor going to a certain part of the screen:

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

This may inspire you to create applications such as pop-up windows or other modal boxes. However, before you can see these in action, you must first process the AJAX request.

3. Handling AJAX requests

Finally, you need to handle AJAX requests on the server side. For WordPress, it's helpful to store all of this in a single file, and you can call them as often as you like.

This part of using HTMX requires you to utilize your PHP skills. Handling AJAX requests will be unique to your particular project. This is where the named properties in the template file are linked to server-side processing.

Of course, you do this whether you use HTMX, JavaScript, or other code. Here's some pseudo-code showing the effect of doing so:

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

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

    $query = new WP_Query( $args );

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

    wp_reset_postdata(); wp_reset_postdata(); wp_reset_postdata(); endif

    wp_reset_postdata(); wp_die(); wp_die()
}

Even so, this may not be relevant to your own project's AJAX handling, or even look like it. The same skills you'll use in building block templates, using PHP extension plugins, and so on can help you make your own AJAX request handlers and functions.

Tips for using HTMX in WordPress

While using HTMX is one of the easiest ways to implement dynamic content in WordPress, it still requires careful management and consideration. There are also ways to improve your development experience.

The first trick has to do with the “maturity“ of HTMX. Currently, it's still a new library on the platform, so it's not as integrated as, say, jQuery.

HTMX is well documented, but there are few resources for integrating the library with WordPress. This means that without the safety net of an existing community, you'll need to do a lot of work to make sure it's running.

One important piece of advice we can offer is to temporarily build your featureinto the plugin. This gives you structure and easier management as you check for bugs and other integration errors.

When it comes to WordPress, we need to understand admin-ajax.php How the file is connected to the rest of the ecosystem, as many interactions 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.
admin-ajax.php file in the code editor.

While HTMX performance is good, it should be ensured that the use of AJAX is low enough so as not to affect the loading speed of the site or search engine optimization. Debugging requests should also be a major part of the workflow, especially with browser development tools in theXMLHttpRequest (XHR)Indicators.

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.
Fetch/XHR requests for the WordPress.org website.

This is a record of request and response data that you can use to debug AJAX requests and application programming interface (API) calls. Given that HTMX is not yet tightly integrated with WordPress, debugging may be more important than debugging other JavaScript frameworks.

summarize

HTMX offers an exciting option for WordPress developers who want to create dynamic, interactive website elements without having their time taken up by complex JavaScript frameworks. It allows you to build directly in HTML and gives you modern interactivity.

In practice, we can use HTMX together with other frameworks, it may not be suitable for all tasks, but his implementation is very simple and provides us with a quick way to build prototypes of interactive elements of a website, if you are interested, you can try the following.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *