Adding page name to the body classes in WordPress

I seem to always have to remind myself of this one… whether it is someone else’s theme I’m dealing with, or an Underscores starter, or for whatever reason the body classes seem insufficient, I always like having the page name in the body classes. This makes it easy to target something that may need to happen on a particular page, and safeguards against the client deleting and re-establishing that page. In any event, if you need the same this is a simple fix. The body_class() function can be filtered and elements added to the array there. You can of course use the page slug or any other detail from the $post object.

//Page Slug Body Class
function add_body_class( $classes ) {
global $post;
if ( isset( $post ) ) {
$classes[] = $post->post_name;
}
return $classes;
}
add_filter('body_class','add_body_class');

Leave a Reply

Your email address will not be published. Required fields are marked *