How to Add Page Slug in Body Class of your WordPress Themes
If you work on WordPress themes on a regular basis, then it is probably best to familiarize yourself with these default WordPress generated CSS cheat sheet. Recently while working on a custom theme project, we found a need to customize certain items based on different pages. WordPress has these things called body classes which outputs the class page, page-template-{filename} and page-id-{number}. We couldn’t use page-id-{number} because page IDs change from development to deployment. We also didn’t want to create a custom page template with repetitive code. We knew that we can keep one thing the same on all of these pages which were page-slugs, so we decided to add page slugs in body class which allowed us to do all the customizations we wanted without any complications. In this article, we will show you how to add page slug in body class of your WordPress themes.
Because this is a theme-specific code, we recommend that you put it in your theme’s functions.php file.
//Page Slug Body Class 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' );
Now you will start seeing a new body class being outputted like this: page-{slug}. Use that class to override your default styles and customize elements for specific pages.
For example, if you were trying to modify a div with widgets class. You can have your css like this:
#sidebar .widgets{background: #fff; color: #000;} .page-education #sidebar .widgets{background: #000; color: #fff;}
Hope you will find this tutorial helpful.