Add page slug to body

Sometimes you may need to add specific class names to the HTML body tag. WordPress has a “body_class” function that outputs the class names to the body element. In this post, I will show you different use cases of the ‘body_class’ and you’ll know the following:

  1. How to add page slug (URL, permalink) to the body class.
  2. How to add a specific CSS class name to the body.

How to add page slug to the body class

Go to your WordPress theme folder and open the “functions.php” file. Copy and paste the following code, and save the file.

function add_page_slug_to_the_body( $classes ) {

global $post;
if ( isset( $post ) ) {
    $classes[] = $post->post_type . '_' . $post->post_name;
  }
  return $classes;
}
add_filter( 'body_class', 'add_page_slug_to_the_body' );

Go to your website & open any page, and now you’ll see the page slug to the HTML body tag. For example- if you open your “Contact” page, then the ‘body’ will contain an extra class name “page_contact.” If you go to your “About” page, then the body will contain the “page_about” class. That means, whatever you see on your page URL/permalink, will be added to the body class as a suffix.

<!-- Output -->
<body class="page-template-default page page-id-15 page_contact">

If you want to replace the underscore (_) with a dash (-), then replace it in the functions.php. Like the below example:

$classes[] = $post->post_type . '-' . $post->post_name;

How to add a specific class name to the body tag

If you want to insert your desired & unique class name to the body tag, then you have to add a parameter to the ‘body_class.’ For example- you want to insert a CSS class name “my-unique-class-name” to the body. The following code will fulfill your goal:

body_class( 'my-unique-class-name' );

To do that, open your “header.php” file and add the above code to the body. See the example below:

<body <?php body_class( 'my-unique-class-name' ); ?>>

The output will look like the following:

<!-- Output -->
<body class="page-template-default page page-id-15 my-unique-class-name">

This is a developer-level post but you don’t have to be an expert to achieve the goal. If you know how to edit your theme file, that will be enough. You can edit your theme file from your hosting/cPanel/Filemanager or FTP. If you don’t know, see another post to create & use an FTP account.

Anyways, now you know how to add a page slug or URL or permalink to the body class, and also you know how to add a custom CSS class name to the body.

There are a few plugins that you can use to add different class names to the body. But you really don’t need to overload your website with an additional plugin that you can achieve with a few lines of code. Also, a plugin contains multiple functionalities that you may don’t need.

If you still have any questions, let me know.