I have already written a couple of articles about body ids: Set a Body Id Using PHP and Setting Body Ids in Expression Engine, but in a recent project, I was looking for a more dynamic way to do it in PHP and WordPress.

I don’t think it’s necessary to discuss the benefits of body ids because I have already discussed them in the other posts. So if you still aren’t using body ids/classes, go read the articles, and start using them.

The Plan

This seems so straightforward that I’m not sure why I didn’t start with this method. So basically, I look at the URI, and if it is equal to / then I give it a body id of home. Otherwise, I grab the first “folder” and set that as the body id.

Example

Let’s say that the URI is: /about/team/leadership/. The body id would be about. Ok, the seems easy, let’s get to the code.

The Code

Here is our setBodyId function:

function setBodyId() {
 $path = $_SERVER['REQUEST_URI'];

 if($path === '/') {
  $bodyId = 'home';
 } else {
  $bodyId = substr($path, 1, (strpos($path,'/',1)-1));
 }
 
 return $bodyId;

If you are using this in WordPress, put this function in your theme function.php file.

Then, you want to call the function and assign it to a variable:

$bodyId = setBodyId(); 

Finally, if the $bodyId variable is not empty, add the id attribute on the body tag:

<body<?php if(!empty($bodyId)) echo ' id="'.$bodyId.'"';?>> 

Conclusion

It’s so simple, yet powerful. This could also easily be recoded in other programming languages. What do you think? Any ideas for improvement?