Skip to content

Instantly share code, notes, and snippets.

@petenelson
Last active February 7, 2024 15:30
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petenelson/50e03ff04eb084de54666b26e7fff5c3 to your computer and use it in GitHub Desktop.
Save petenelson/50e03ff04eb084de54666b26e7fff5c3 to your computer and use it in GitHub Desktop.
WordPress: Output CSS classes
/**
* Outputs a list of sanitized CSS class names.
*
* @param array|string $classes List of class names (array or string with
* class names separated by spaces or commas).
* @param bool $echo Echo the list of class names (defaults to true).
* @return void|array
*/
function output_css_classes( $classes, $echo = true ) {
// Append everything into a string.
$class_list = '';
if ( is_string( $classes ) ) {
$class_list = str_replace( ',', ' ', $classes );
}
// Account for any elements in the array that could have multiple classes
// separated by spaces or commas.
if ( is_array( $classes ) ) {
foreach ( $classes as $class ) {
$class_list .= str_replace( ',', ' ', $class ) . ' ';
}
}
// Cleanup the class list.
$class_list = explode( ' ', $class_list );
$class_list = array_map( 'sanitize_html_class', $class_list );
$class_list = array_map( 'trim', $class_list );
$class_list = array_filter( $class_list );
$classes = implode( ' ', $class_list );
if ( $echo ) {
echo $classes; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}
return $classes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment