Created
November 14, 2018 01:56
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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