Skip to content

Instantly share code, notes, and snippets.

@MaximeCulea
Last active February 17, 2020 09:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MaximeCulea/4569a9660e88ccf79d4038d1608ba469 to your computer and use it in GitHub Desktop.
Save MaximeCulea/4569a9660e88ccf79d4038d1608ba469 to your computer and use it in GitHub Desktop.
Ease the use of body classes into template.
<?php class MC_Body_Class {
private static $instance;
private $body_class = [];
private $delete_class = [];
private function __construct() {
self::$instance = $this;
add_filter( 'body_class', array( $this, 'body_class' ) );
}
public static function get_instance() {
if ( is_null( self::$instance ) ) {
self::$instance = new MC_Body_Class();
}
return self::$instance;
}
/**
* Add a body class
*
* @param $body_class array | String
*
* @author Maxime Culea
*
*/
public function add( $body_class ) {
$this->body_class[] = $body_class;
}
/**
* Stack unwanted body_classes
*
* @param $body_class String
*
* @author Maxime Culea
*
*/
public function delete( $body_class ) {
$this->delete_class[] = $body_class;
}
/**
* Manage to merge the class's body class array with filter ones
*
* @param $classes
*
* @author Maxime CULEA
*
* @return array
*/
public function body_class( $classes ) {
if ( is_array( $this->body_class ) ) {
foreach ( $this->body_class as $bd ) {
$classes[] = $bd;
}
} else {
$classes[] = $this->body_class;
}
// Filter body classes
return array_filter( $classes, [ $this, 'delete_wanted_body_classes' ] );
}
/**
* Filter method which handle to delete wanted body_class
*
* @param $class
*
* @author Maxime CULEA
*
* @return bool
*/
private function delete_wanted_body_classes( $class ) {
return ! in_array( $class, $this->delete_class );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment