Custom Class on a Specific Page Template

You can use conditional tags to add custom classes to specific pages only. Here’s an example of adding a class only for a specific page template.

1

2

3

4

5

6

7

8

9

10

add_filter('body_class','codismo_body_class');

functioncodismo_body_class($classes){

if(is_page_template('template-home.php')){

$classes[]='custom-class';

}

return$classes;

}

Custom Class if a Sidebar Has Widgets

Let’s say you want to do some CSS adjustments in case there’s no widgets added to the sidebar ( for example make the content full width or center it, so it doesn’t look out of place ).

1

2

3

4

5

6

7

8

9

10

add_filter('body_class','codismo_body_class');

functioncodismo_body_class($classes){

if(!is_active_sidebar('sidebar-1')){

$classes[]='custom-class';

}

return$classes;

}

You could also go the other way around, add a class if there are widgets in the sidebar.

1

2

3

4

5

6

7

8

9

10

add_filter('body_class','codismo_body_class');

functioncodismo_body_class($classes){

if(is_active_sidebar('sidebar-1')){

$classes[]='custom-class';

}

return$classes;

}

Custom Class if a Navigation Menu is Empty

So, what if you want to make adjustments in case the primary menu is empty. For example you have the usual header layout with the logo on the left and navigation on the right, but if there’s no navigation you want to center the logo.

1

2

3

4

5

6

7

8

9

10

add_filter('body_class','codismo_body_class');

functioncodismo_body_class($classes){

if(!has_nav_menu('primary')){

$classes[]='custom-class';

}

return$classes;

}

Removing Classes

Important: You shouldn’t be doing this, the classes WordPress adds are there for a reason. But if it’s for your own purposes ( not a theme available for others ) and you want to remove some classes, you can do it like this.

The following code removes all the classes:

1

2

3

4

5

6

7

8

add_filter('body_class','codismo_body_class');

functioncodismo_body_class($classes){

$classes=array();

return$classes;

}

Or in case you want to remove a specific class:

1

2

3

4

5

6

7

8

9

10

add_filter('body_class','codismo_body_class');

functioncodismo_body_class($classes){

if(in_array('some-class',$classes)){

unset($classes[array_search('some-class',$classes)]);

}

return$classes;

}

Final Words

This concludes the first tutorial in the WPDev101 series ( WordPress development basics ). In case you have any questions just let me know down in the comments.