Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Generate a class attribute from an array of classes and sanitises the classes
// Example.
$myclasses = [ 'my-class', 'some-other-class', '<script>console.log(hi);</script>' ];
'<div %1$s>%2$s</div>',
cameronjonesweb_generate_class_attribute( $myclasses ),
'My content'
// Displays: ?>
<div class="my-class some-other-class scriptconsoleloghiscript">My content</div>
* Generates a class attribute for a HTML element and sanitises the classes
* We can't just run `sanitize_html_class` on imploded classes as the spaces will be stripped out
* So we have to loop through each class and sanitise each class individually
* @param array $classes The classes to add to the element.
* return string The generated class attribute, or an empty string if the array is empty
function cameronjonesweb_generate_class_attribute( $classes ) {
$class_attr = ! empty( $classes ) && is_array( $classes ) ? 'class="' . implode( ' ', array_map( function( $class ) {
return sanitize_html_class( $class );
}, $classes ) ) . '"' : '';
return $class_attr;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.