a:2:{i:0;a:1:{s:4:"data";a:1:{s:7:"entries";a:1:{i:0;a:7:{s:2:"id";s:3:"128";s:5:"title";s:32:"Dynamically Set a Body Id in PHP";s:11:"displayDate";s:10:"03.10.2009";s:13:"attributeDate";s:10:"2009-03-10";s:4:"body";s:2137:"

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?

";s:13:"numberOfLikes";N;s:10:"bodyBlocks";a:0:{}}}}}i:1;O:25:"yii\caching\TagDependency":3:{s:4:"tags";a:4:{i:0;s:7:"element";i:1;s:29:"element::craft\elements\Entry";i:2;s:40:"element::craft\elements\Entry::section:4";i:3;s:7:"graphql";}s:4:"data";a:4:{s:40:"CraftCMSce35088bdfe0816226cd17fd051a4803";s:21:"0.70573500 1736501960";s:40:"CraftCMS2743a789e8993267a348eee1ee7e4450";s:21:"0.67537500 1713205687";s:40:"CraftCMS2ac34726f299f7e18e449d8e536c67f8";s:21:"0.84529700 1741778847";s:40:"CraftCMS3817d4a648fcfac939af46605323feb0";s:21:"0.36746500 1735923287";}s:8:"reusable";b:0;}}