Conditionally Add a Class to the Body Class Tag
In this short tutorial, I will describe how I added a class to WordPress’s body_class
tag inside of an if statement.
Upon having my newest theme reviewed for possible inclusion at wordpress.org, the reviewer noted that I should include the conditional class within functions.php instead of within header.php. So after looking at the Codex page for body class, I used the filter method, described below.
// Add specific CSS class by filter add_filter( 'body_class', 'my_class_names' ); function my_class_names( $classes ) { // add 'class-name' to the $classes array $classes[] = 'class-name'; // return the $classes array return $classes; }
I originally modified functions.php for my theme like so:
function urban_square_bodyclass_names( $classes ) { // if we are not in a mobile environment if ( !wp_is_mobile() ) { // add 'desktop' to the $classes array $classes[] = 'desktop'; return $classes; } } add_filter( 'body_class', 'urban_square_bodyclass_names' );
Since I saw all of the body class tags with the addition of my desktop class, I thought everything was a done deal. That was until I viewed the theme on my mobile phone and was greeted by something like these two wonderful error messages:
PHP Warning: array_unique() expects parameter 1 to be array, null given in /var/www/wordpress/wp-includes/post-template.php on line 682
PHP Warning: join(): Invalid arguments passed in /var/www/wordpress/wp-includes/post-template.php on line 499
After panicking and then Googling, I found out that the error messages were associated with the body class tag (other mentions of this error code showed the word class). I figured out that this was because the body class if statement did not have an else part to determine what to do when we are in a mobile environment. It was returning nothing, showing body class
with nothing after it in the frontend code. Thus, I adjusted the conditional to return $classes, as shown below:
function urban_square_bodyclass_names( $classes ) { // if we are not in a mobile environment if ( !wp_is_mobile() ) { // add 'desktop' to the $classes array $classes[] = 'desktop'; return $classes; } else { return $classes; } } add_filter( 'body_class', 'urban_square_bodyclass_names' );
Now there are no errors in mobile. Yeah!