Enhancing WordPress Archives with HTMX and View Transitions

Manos Menexis
Posted by Manos Menexis

6 minutes read

Making WordPress post archives interactive has never been easier. Learn how to implement HTMX for real-time AJAX filtering and seamless page transitions, all while keeping your site lightning-fast and performant.

Introduction

On a previous article, I look into the topic of programmatically filtering post archives in WordPress. Today, I will be using HTMX and the View Transitions to elevate the user experience. These technologies enable real-time filter updates without requiring a page reload, and offer slick animations with minimal code adjustments.

The benefits of HTMX

HTMX opens the door to a range of modern web features like AJAX, CSS Transitions, WebSockets, and Server-Sent Events via HTML attributes.

Key Advantages:

  • Simplicity & Reduced JavaScript: HTMX lets you implement dynamic web behaviours directly from HTML, thereby reducing dependency on JavaScript or elaborate frontend frameworks.
  • Progressive Enhancement: It encourages a design that works without JavaScript, ensuring base functionality remains accessible, and then enhances the experience when JavaScript is available.
  • Lightweight & Performant: Lighter than most frontend frameworks, HTMX leads to quicker load times and fewer client-side errors.
  • Modern Web Features with Seamless Integration: It offers native support for modern web features and can be seamlessly incorporated into existing tech stacks.

For an in-depth understanding, visit the official HTMX documentation.

The View Transitions API

The View Transitions API provides a mechanism for easily creating animated transitions between different DOM states while also updating the DOM contents in a single step.

Designed primarily to introduce app-like transitions into Multi-Page Applications (MPAs), the View Transitions API is a noteworthy advancement. Unlike specialised libraries in frameworks like React, this API offers the same fluid transitions without the overhead of additional packages. You can learn more from the MDN documentation.

Starting code

For this example, I’ll use categories as filters and allow sorting by date in ascending or descending order. I’ll also include HTMX directly in the markup as a script. Although in real-world applications, it’s advisable to include it in the head section or load it via a package manager like npm. This tutorial uses Twig, but you can easily adapt it to vanilla WordPress.

Below is the markup before we introduce HTMX:

<main class="grid-post-archives">
  <div class="container">
    <h1>Post Archives</h1>
    <div data-ref="content">
      <!-- Form -->
      <form method="get">
        <!-- Categories -->
        <fieldset>
          <legend>Category</legend>
          {% for term in terms %}
            <input
              id="{{ term.id }}"
              name="cat[]"
              value="{{ term.id }}"
              type="checkbox"
              {{ term.selected ? "checked" }}
            />
            <label for="{{ term.id }}">{{ term.name }}</label>
          {% endfor %}
        </fieldset>
        <!-- Order -->
        <fieldset>
          <legend>Order</legend>
          <input
            id="order-asc"
            name="order"
            value="ASC"
            type="radio"
          />
          <label for="order-asc">Ascending</label>
          <input
            id="order-desc"
            name="order"
            value="DESC"
            type="radio"
          />
          <label for="order-desc">Descending</label>
        </fieldset>
        <input type="submit">
      </form>
      <!-- Posts Loop -->
      {% if posts|length > 0 %}
        <ul data-ref="posts" class="posts resetList">
          {% for post in posts %}
            <li class="post">
              <img src="{{ post.thumbnail.src }}" alt="">
              <h3>{{ post.title }}</h3>
              <p>{{ post.excerpt }}</p>
            </li>
          {% endfor %}
        </ul>
      {% else %}
        <p class="posts-empty">No posts found</p>
      {% endif %}
    </div>
  </div>
</main>

This is what a regular archive page would look like. If you followed my previous article you know that when submitting the form the selected options will be added to the url as params and the page will reload to reflect our selected filters.

Adding HTMX attributes

Adding HTMX attributes turns this into a dynamic, AJAX-powered form. Let’s look at the final markup and decipher what each attribute accomplishes:

<script src="https://unpkg.com/htmx.org@1.9.6"></script>
<main 
	class="grid-post-archives" 
	hx-boost="true"
>
  <div class="container">
    <h1>Post Archives</h1>
    <div data-ref="content">
      <form
        method="get"
        hx-push-url="true"
        hx-get="{{ post.link }}"
        hx-target="closest [data-ref='content']"
        hx-select="[data-ref='content']"
        hx-swap="outerHTML show:body:top"
        hx-trigger="change"
      >
	    <!-- Categories -->
        <!-- Order -->
        <noscript>
	      <input type="submit">
        </noscript>
      </form>
	  <!-- Posts Loop -->    
    </div>
  </div>
</main>

The attributes

  • hx-boost=”true”: Transforms anchor tags and forms into AJAX requests.
  • hx-push-url="true": Updates the browser URL to preserve the state across navigation and page refreshes.
  • hx-get="{{ post.link }}": Specifies the content source url (in this case is the link of our post archive page).
  • hx-target="closest [data-ref='content']": Identifies the element to update. It can also be a class or an id among other things. I went with a data attribute to make it more clear.
  • hx-select="[data-ref='content']": Determines what content will replace the target.
  • hx-swap="outerHTML show:body:top": Defines the swapping action and scrolls to the top of the page.
  • hx-trigger="change": Provide the event that initiates the swap. I chose the change event in this case, to provide instant feedback to the users selection.

For users with JavaScript disabled, I wrapped the submit button with a noscript tag that will allow them to still submit the form manually.

And that’s it. We now have a fully functional AJAX-driven filtering functionality for your post archives.

Leveraging View Transitions with HTMX

HTMX offers out-of-the-box support for View Transitions through a single configuration variable. This means no extra code is necessary to leverage this feature.

<script src="https://unpkg.com/htmx.org@1.9.6"></script>
<script>
  htmx.config.globalViewTransitions = true
</script>

This action adds a default fade animation to content updates. By adding the view-transition-name property the browser will add animated transitions between common elements.

<li
  class="post"
  style="view-transition-name: post-{{ post.id }}"
>
  <img src="{{ post.thumbnail.src }}" alt="">
  <h3>{{ post.title }}</h3>
  <p>{{ post.excerpt }}</p>
</li>

You can even create custom CSS animations using the View Transitions API and create a unique User Experience for the visitors of your website.

View transitions as a progressive enhancement

While the View Transitions API is experimental and not universally supported, it serves as a progressive enhancement, ensuring your website remains functional.

By following this guide, you’ll have a WordPress post archive that not only filters posts via AJAX but also offers a polished, app-like user experience.

Conclusion

In this exploration of enhancing post archive filters in WordPress, HTMX and the View Transitions proved to be game-changers for user experience. By leveraging HTMX, the complexity of the codebase is dramatically reduced and the reliance on frontend frameworks or libraries is obsolete. This makes the web page lighter, faster, and less prone to client-side bugs, without compromising on modern functionalities like AJAX requests and seamless transitions.

The View Transitions API further amplifies the experience, enabling fluid transitions between different DOM states. It allows websites to offer an app-like feel, taking user engagement to a new level. Moreover, the progressive enhancement approach ensures that these features act as bonuses for supported browsers, not prerequisites for accessing content.

If you’re a developer interested in modern web technologies and keen to improve your WordPress projects, HTMX and the View Transitions API present a compelling case for further investigation. With minimal code changes, these tools can help you build an enhanced, interactive, and modern UI that stands out.

While the View Transitions API is still experimental, it shows significant promise. The power of these tools is in our hands to explore, integrate, and enhance. Happy coding!

Download the Flynt Component from Github

More Posts

We help your WordPress website and business stay ahead of the curve.

Contact Us