Most WordPress themes have (or should have) their opening body tag look like this:

<body <?php body_class(); ?>>

the body_class function will print all sorts of awesome classes which are relevant to your current page view. Among them it will print out the current post/page ID, something like: <body class="page page-id-8 logged-in admin-bar antialiased">

The Problem

Now this is extremely helpful already as is when needed to target niche situations with your CSS, JS etc.. but isn’t as semantic as it could be. Having “page-id-8” is all well and good about wouldn’t it be nice to have it print out “page-about” as well?

The Solution

This handy filter will print the current page or post’s slug:

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

Add this to your theme’s functions.php file.

When you save and inspect your site in the front end you should now see your slug in your body tag for something much more readable!

Originally published on

Leave a Reply

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

Have Any Questions?

Speak with a
Digital Expert

  • Looking to increase leads?
  • Maximize profits?
  • Redesign your website?
  • Sell Online?
  • Build an App?

Let's Discuss Your Next Project

  • This field is for validation purposes and should be left unchanged.