Add Body Classes in WordPress

Wordpress allows you to add extra CSS classes to the <body> element by hooking into the ‘body_class’ filter.

The function below adds a CSS class based on the post URL. For this post, the new class would be ‘add-body-classes-in-wordpress’. This uses the PHP function basename(), which returns the trailing name component of the path.

It also adds a class based on the user role, if the user is logged in.