Menü schliessen
Created: February 28th 2024
Last updated: March 16th 2024
Categories: Common Web Development,  Php,  Wordpress
Author: Tim Fürer

WordPress: How to generate HTML class attribute with array of strings

Tags:  function,  guide,  PHP,  wordpress
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

In WordPress development, efficiently managing HTML class attributes can often become a cumbersome task, leading to code clutter and decreased readability. To address this challenge, we introduce a helper function designed to streamline the generation of HTML class attributes within WordPress projects.


Helper Function

<?php

function classes($classes = []) {
    $classes = array_filter($classes, fn($item) => !empty($item));

    if (empty($classes)) {
        return ';';
    }

    ob_start();

    ?>

    class="<?= esc_attr(implode(' ', $classes)) ?>"

    <?php

    return ob_get_clean();
}

?>

Benefits

Filtering
A common challenge is handling optional classes. The classes function filters out empty or falsy values, ensuring that only valid classes are included in the attribute.

Output Escaping
The function utilizes the esc_attr function to escape individual classes, thereby mitigating the risk of XSS (Cross-Site Scripting) vulnerabilities.

Simple Usage
By encapsulating class attribute generation within a single function call, developers can achieve cleaner and more concise code. This approach reduces complexity and improves code maintainability.


Usage

<?php

echo classes(['foo', '', 'bar', $condition ? 'fizz' : 'buzz', $other_condition ? 'optional' : '']);

?>

In this example, an array of classes is passed to the classes function. The function filters out empty strings and falsey values, resulting in a sanitized and optimized class attribute output.