Add Page Slug to Body Class in WordPress

One of my favorite feature when it comes to theme development in WordPress is the concept of body class. For a deliberate design, you not necessarily need to use these classes but it can be useful in a lot of cases.

One of the scenario if you want to target a specific page. The need for page targeting in CSS can happen in a lot of situation and it is better to create a slug based class than using the default ID based.

By default, you only get post-id-* classes and you can’t identify the page correctly; this is where the body_class filter comes in the picture.

function pine_add_page_slug_body_class( $classes ) {
    global $post;
    
    if ( isset( $post ) ) {
        $classes[] = 'page-' . $post->post_name;
    }
    return $classes;
}

add_filter( 'body_class', 'pine_add_page_slug_body_class' );

You can create any conditional check if needed. If you want to know more about the body_class filter please visit the official documentation!