<p>I have already written a couple of articles about body ids: <a href="//trevor-davis.com/blog/tutorial/set-a-body-id/">
Set a Body Id Using PHP</a> and <a href="//trevor-davis.com/blog/tutorial/setting-body-ids-in-expression-engine/">Setting Body Ids in Expression Engine</a>, but in a recent project, I was looking for a more dynamic way to do it in PHP and WordPress.</p>

<p>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.</p>

<h2>The Plan</h2>
<p>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 <strong>/</strong> then I give it a <strong>body id of home</strong>. Otherwise, I grab the <strong>first “folder” and set that as the body id</strong>.</p>

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

<h2>The Code</h2>

<p>Here is our setBodyId function:</p>

<div class="codeblock"><code>
function setBodyId() {<br /> $path = $_SERVER['REQUEST_URI'];<br /><br /> if($path === '/') {<br />  $bodyId = 'home';<br /> } else {<br />  $bodyId = substr($path, 1, (strpos($path,'/',1)-1));<br /> }<br /> <br /> return $bodyId;<br />} 

</code></div>
<p class="note"><em>If you are using this in WordPress, put this function in your theme function.php file.</em></p>

<p>Then, you want to call the function and assign it to a variable:</p>

<div class="codeblock"><code>
$bodyId = setBodyId(); 

</code></div>

<p>Finally, if the $bodyId variable is not empty, add the id attribute on the body tag:</p>
<div class="codeblock"><code>
&lt;body&lt;?php if(!empty($bodyId)) echo ' id="'.$bodyId.'"';?&gt;&gt; 

</code></div>

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