Last active
February 7, 2024 15:30
-
-
Save petenelson/50e03ff04eb084de54666b26e7fff5c3 to your computer and use it in GitHub Desktop.
WordPress: Output CSS 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
/** | |
* 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