Could we help you? Please click the banners. We are young and desperately need the money
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.
<?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();
}
?>
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.
<?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.