Skip to content

Instantly share code, notes, and snippets.

@cameronjonesweb
Created November 14, 2018 01:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cameronjonesweb/7b89879192331bfd831a387d7b366649 to your computer and use it in GitHub Desktop.
Save cameronjonesweb/7b89879192331bfd831a387d7b366649 to your computer and use it in GitHub Desktop.
Generate a class attribute from an array of classes and sanitises the classes
<?php
// Example.
$myclasses = [ 'my-class', 'some-other-class', '<script>console.log(hi);</script>' ];
printf(
'<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>
<?php
/**
* 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