Skip to content

Instantly share code, notes, and snippets.

@DaveyJake
Last active May 19, 2018 06:31
Show Gist options
  • Save DaveyJake/96ce82a3de1aef05e146ddd80a336f55 to your computer and use it in GitHub Desktop.
Save DaveyJake/96ce82a3de1aef05e146ddd80a336f55 to your computer and use it in GitHub Desktop.
Custom WordPress Function: body_has_class
<?php
/**
* Custom WordPress function to check if the HTML body `class` attribute
* contains one or many specified `className` values.
*
* @author Davey Jacobson <djacobson@usarugby.org>
* @version 1.0.0
*/
if ( ! function_exists( 'body_has_class' ) ) {
/**
* Check if the `body` has one or many specified classes.
*
* @example {
* Checking for a single class:
*
* `if ( body_has_class( 'this-html-class' ) ) { ... }`
*
* Checking for multiple classes:
*
* `if ( body_has_class( array( 'random-class__1', 'random-class-two' ) ) ) { ... }`
* }
*
* @param string|array $class Class or classes to check for.
* @return bool True if found. False if not found.
*/
function body_has_class( $class = null ) {
// Fail silently if `$class` is not provided.
if ( is_null( $class ) ) {
return false;
}
else {
// Final boolean result.
static $body_class = null;
// Retrieve the current body `classList` as an array.
$classes = get_body_class();
if ( is_string( (string) $class ) ) {
$body_class = ( in_array( $class, $classes ) ? true : false );
}
elseif ( is_array( (array) $class ) ) {
/**
* Borrowed from `in_array_any`
*
* @author Rok Kralj
* @see {@link https://stackoverflow.com/a/11040612/1155068}
*/
$body_class = !!array_intersect( $class, $classes );
}
// Final check to make sure there's a result.
if ( ! is_null( $body_class ) ) {
return $body_class;
}
// Default to `false` otherwise.
else {
return false;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment