Wordpress 7 Gallery Lightbox Breaks Bootscore-Based Themes

The new gallery lightbox navigation added in WordPress 7 is super cool! However, when a lightbox is opened in WordPress 7, it adds the inert attribute to all direct children of the <body> element. At UF, we used a Bootscore-based WordPress theme (a boilerplate Bootstrap CSS enabled theme), which wraps the site content in a <div id="page" class="site"> (see header.php), causing the entire site to go “inert” when the gallery lightbox is opened–not ideal.

Here is a temporary fix you can add to a Bootscare-based theme to work around this behavior. I have not tested it comprehensively, but I have confirmed it works on my theme in a development environment. I simply added this to my main “scripts.js” file enqueued by my functions.php.

This function uses the MutationObserver interface, which I haven’t messed with much. Importantly, notice how observer.disconnect(); stops the observer before removing the unwanted inert attribute, then restarts with observer.observe(); afterward. This is to avoid removeAttribute(); from triggering the observer. If your callback function modifies the exact same node or attributes that it is watching, you must disconnect it first to prevent an endless cycle of self-triggering.

1// Enqueue the script in functions.php if needed.
2add_action('wp_enqueue_scripts', function () {
3    wp_enqueue_script('my-theme-script', get_stylesheet_directory_uri() . '/script.js', []);
4});
 1// my-theme/script.js
 2// WordPress 7.0 Lightbox fix for #page.site inert conflict
 3
 4document.addEventListener('DOMContentLoaded', () => {
 5  const page = document.querySelector('#page.site');
 6  if (!page) return;
 7  
 8  const config = { attributes: true };
 9  
10  const observer = new MutationObserver((mutationsList) => {
11      for (const mutation of mutationsList) {
12          if (mutation.type === 'attributes' && mutation.attributeName === 'inert') {
13              if (page.hasAttribute('inert')) {
14                  observer.disconnect(); 
15                  page.removeAttribute('inert'); 
16                  observer.observe(page, config); 
17              }
18          }
19      }
20  });
21  
22  observer.observe(page, config);
23});

Ideally, the inert attributes would be added to the direct children of the <div id="page" class="site"> wrapper rather than the <body> element when a lightbox is opened. I have not explored that, but this WordPress core commit seems to be the root of the issue (specifically, lines 133-143). Essentially, if you site content is nested in any element within <body> and not <body> directly, you’re going to have problems with the gallery lightbox navigation introduced in WordPress 7.

tags: wordpresscodejavascriptdomwork