Collapsible Sidebar Widgets on Phones
Folds sidebar and footer widgets into tap-to-open sections on small screens, so visitors reach the content and footer without scrolling past long widget lists.
Opens WPIDE on
Code
<style>
.wpide-widget-toggle{display:flex;justify-content:space-between;align-items:center;width:100%;padding:.6em 0;border:0;border-bottom:1px solid rgba(0,0,0,.12);background:none;color:inherit;font:inherit;font-weight:700;text-align:left;cursor:pointer;}
.wpide-widget-toggle::after{content:"+";font-size:1.3em;line-height:1;}
.wpide-widget-toggle[aria-expanded="true"]::after{content:"\2212";}
.wpide-widget-body[hidden]{display:none;}
</style>
<script>
(function () {
var breakpoint = 768;
if (window.innerWidth >= breakpoint) { return; }
document.querySelectorAll('.widget-area .widget, .sidebar .widget, .widget-area .wp-block-group').forEach(function (widget, i) {
var title = widget.querySelector(':scope > .widget-title, :scope > .widgettitle, :scope > h2, :scope > .wp-block-heading');
if (!title || widget.querySelector('.wpide-widget-toggle')) { return; }
var body = document.createElement('div');
body.className = 'wpide-widget-body';
body.id = 'wpide-widget-body-' + i;
body.hidden = true;
while (title.nextSibling) { body.appendChild(title.nextSibling); }
var btn = document.createElement('button');
btn.type = 'button';
btn.className = 'wpide-widget-toggle';
btn.setAttribute('aria-expanded', 'false');
btn.setAttribute('aria-controls', body.id);
btn.textContent = title.textContent;
btn.addEventListener('click', function () {
var open = btn.getAttribute('aria-expanded') !== 'true';
btn.setAttribute('aria-expanded', open ? 'true' : 'false');
body.hidden = !open;
});
title.textContent = '';
title.appendChild(btn);
widget.appendChild(body);
});
})();
</script>
Notes
Works with widgets that have a title (classic widget titles or a Heading block as the first item). Change the breakpoint at the top of the script.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.