Quickly add the page slug to body tag as an ID with two simple steps.
Before we get started here’s a quick look at the finalized outcome of the code when you add the page slug to body tag as an ID:
As you can see it takes the page slug and uses it as the ID within the body tag.
This trick can be a great way to easily target specific pages with css or jquery/js.
I generally like to build this into my themes as I find it comes in handy. In a recent project we had a ton of inner pages all using the same template. Right before the project was ready to go live the designer decided to add a specific functionality to two of the inner pages. Instead of creating a new template for these two pages I just used the body ID in my stylesheet to quickly adjust the design on those two specific pages.
Here’s how to get it done.
Step 1: Open you themes functions.php file and enter the following code:
Note: If your website is in a subdirectory you can change the code to the following:
Step 2: Open your themes header.php and edit the following.
Here you can see what it looks like when you switch pages. By default it will add the id of ‘home’ when you are on the page you designated as your homepage in WordPress.
Overall this is just some simple code that can help out with development.