This is a life saver when it comes to theming websites. WordPress add page slug to body CSS class is a neat trick to make thing easier in the theming department.
WordPress add page slug to body CSS class
Let say you have a page that has the URL or /about-us
. Wouldn’t it make sense to have a CSS class in the body with page-slug-about-us
to make theming easier?
The following snippet will do just that if you add it to your themes function.php
file.
/**
* Add Page Slug Body Class
*
*/
function lehel_add_slug_body_class( $classes ) {
if (is_single() ) {
global $post;
if ( isset( $post ) ) {
$classes[] = $post->post_type . '-slug-' . $post->post_name;
}
return $classes;
}
}
add_filter( 'body_class', 'lehel_add_slug_body_class' );
Once you have this running you can now do custom styles in your CSS file based on the URL of the page.
body.page-slug-about-us{
/* Awesome CSS goes here */
}
In the code snippet above I am using the body_class
hook, to know more about it visit it’s WordPress code reference page.
Like the page if you found the useful! Cheers!