Building a WordPress Accordion Block (No Javascript Required)

Creating an accordion block in WordPress can enhance user interaction and improve the layout of your content. This guide will take you through the steps required to build a simple accordion block without requiring any JavaScript.

What is an Accordion Block?

An accordion block is a UI element that allows users to expand and collapse sections of content. This can make your post or page more streamlined and engaging.

Why Choose No Javascript?

Building an accordion block without JavaScript can improve performance and compatibility, especially in cases where JavaScript is disabled. It’s a great way to ensure that your content is accessible to a broader audience.

Step-by-Step Guide

Step 1: Set Up Your Block Plugin

Begin by creating a basic WordPress plugin that will house your new block. Here’s a simple structure:

<?php
/**
 * Plugin Name: Accordion Block
 */

function accordion_block_register() {
    register_block_type('custom/accordion', [
        'render_callback' => 'accordion_block_render'
    ]);
}
add_action('init', 'accordion_block_register');

Step 2: Add Your Block's HTML Structure

You’ll need to define the HTML structure for the accordion in your accordion_block_render function. Here’s an example:

function accordion_block_render($attributes, $content) {
    return '<div class="accordion">' . $content . '</div>';
}

Step 3: Style the Accordion

Add some basic CSS to style your accordion and manage the expand/collapse functionality. You can achieve this using the :target pseudo-class:

.accordion div {
    display: none;
}
.accordion div:target {
    display: block;
}

Step 4: Insert Content into the Block

You can insert content into your accordion block by using the WordPress block editor. Create multiple sections, each containing a title and content.

Conclusion

This simple accordion block offers a clean solution for presenting collapsible content without relying on JavaScript. It ensures a faster load time and better accessibility, making it a valuable addition to your WordPress site.

By following the above steps, you’ll be able to implement a fully functional accordion block that enhances user experience.