Skip To Content

Adding the slug to A body tag in WordPress

Kevin Doherty

Creative Director

Date

Jun. 12, 2015

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!

Book with us

Let’s accomplish what you are looking for, our team of experts are here for you.

Let's work together

Warning: Working with our team may result in excessive creativity, uncontrollable 'aha' moments, and an addiction to perfect pixels. Please proceed with caution.