Skip To Content

Adding the slug to A body tag in WordPress

Development

Kevin Doherty Creative Director

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!

Comments

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

Request a Quote

If you’re ready to change the trajectory of your business and
excited to partner with the right team to get the job done.

UP

© 2024 NVISION. All Rights Reserved.