Skip to content

Instantly share code, notes, and snippets.

@bradyvercher
Last active October 13, 2015 13:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradyvercher/4204333 to your computer and use it in GitHub Desktop.
Save bradyvercher/4204333 to your computer and use it in GitHub Desktop.
WordPress: Template tag to allow for easily filtered CSS classes across templates. (http://www.blazersix.com/blog/wordpress-class-template-tag/)
<?php
/**
* WordPress template tag to allow for CSS classes to be easily filtered across templates.
*
* @author Brady Vercher (twitter.com/bradyvercher)
* @link http://www.blazersix.com/blog/wordpress-class-template-tag/
*
* @param string $id Element identifier.
* @param array|string $classes Optional. List of default classes as an array or space-separated string.
* @param array|string $args Optional. Override defaults.
* @return null|array Null when displaying, otherwise an array of classes.
*/
function blazersix_class( $id, $classes = array(), $args = array() ) {
$id = sanitize_key( $id );
$args = wp_parse_args( (array) $args, array(
'echo' => true,
'post_id' => null
) );
if ( ! empty( $classes ) && ! is_array( $classes ) ) {
// Split a string.
$classes = preg_split( '#\s+#', $classes );
} elseif ( empty( $classes ) ) {
// If the function call didn't pass any classes, use the id as a default class.
// Otherwise, the calling function can pass the id as a class along with any others.
$classes = array( $id );
}
// Add support for the body element.
if ( 'body' == $id ) {
$classes = array_merge( get_body_class(), $classes );
}
// Add support for post classes.
if ( 'post' == $id ) {
$classes = array_merge( get_post_class( '', $args['post_id'] ), $classes );
}
// A page template should set modifier classes all at once in the form of an array.
$class_mods = apply_filters( 'blazersix_class', array(), $id, $args );
if ( ! empty( $class_mods ) && isset( $class_mods[ $id ] ) ) {
$mods = $class_mods[ $id ];
// Split a string.
if ( ! is_array( $mods ) ) {
$mods = preg_split( '#\s+#', $mods );
}
foreach( $mods as $key => $mod ) {
// If the class starts with a double minus, remove it from both arrays.
if ( 0 === strpos( $mod, '--' ) ) {
$unset_class = substr( $mod, 2 );
unset( $mods[ $key ] );
unset( $classes[ array_search( $unset_class, $classes ) ] );
}
}
$classes = array_merge( $classes, $mods );
}
// Last chance to modify.
$classes = apply_filters( 'blazersix_classes', $classes, $id, $args );
$classes = apply_filters( 'blazersix_classes-' . $id, $classes, $args );
if ( $args['echo'] ) {
echo 'class="' . join( ' ', array_map( 'sanitize_html_class', $classes ) ) . '"';
} else {
return esc_attr( $classes );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment