{"authorId":"1","title":"Dynamically Set a Body Id in PHP","slug":"dynamically-set-a-body-id-in-php","postDate":1236735506,"expiryDate":null,"enabled":"1","fields":{"2":"<p>I have already written a couple of articles about body ids: <a href=\"http:\/\/trevordavis.net\/blog\/tutorial\/set-a-body-id\/\">\nSet a Body Id Using PHP<\/a> and <a href=\"http:\/\/trevordavis.net\/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>\n<!--more-->\n<p>I don&rsquo;t think it&rsquo;s necessary to discuss the benefits of body ids because I have already discussed them in the other posts. So if you still aren&rsquo;t using body ids\/classes, go read the articles, and start using them.<\/p>\n\n<h2>The Plan<\/h2>\n<p>This seems so straightforward that I&rsquo;m not sure why I didn&rsquo;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 &ldquo;folder&rdquo; and set that as the body id<\/strong>.<\/p>\n\n<h3>Example<\/h3>\n<p>Let&rsquo;s say that the URI is: <strong>\/about\/team\/leadership\/<\/strong>. The body id would be <strong>about<\/strong>. Ok, the seems easy, let&rsquo;s get to the code.<\/p>\n\n<h2>The Code<\/h2>\n\n<p>Here is our setBodyId function:<\/p>\n\n<div class=\"codeblock\"><code>\nfunction&nbsp;setBodyId()&nbsp;&#123;<br \/>&nbsp;$path&nbsp;=&nbsp;$_SERVER&#91;'REQUEST_URI'&#93;;<br \/><br \/>&nbsp;if($path&nbsp;===&nbsp;'\/')&nbsp;&#123;<br \/>&nbsp;&nbsp;$bodyId&nbsp;=&nbsp;'home';<br \/>&nbsp;&#125;&nbsp;else&nbsp;&#123;<br \/>&nbsp;&nbsp;$bodyId&nbsp;=&nbsp;substr($path,&nbsp;1,&nbsp;(strpos($path,'\/',1)-1));<br \/>&nbsp;&#125;<br \/>&nbsp;<br \/>&nbsp;return&nbsp;$bodyId;<br \/>&#125;&nbsp;\n\n<\/code><\/div>\n<p class=\"note\"><em>If you are using this in WordPress, put this function in your theme function.php file.<\/em><\/p>\n\n<p>Then, you want to call the function and assign it to a variable:<\/p>\n\n<div class=\"codeblock\"><code>\n$bodyId&nbsp;=&nbsp;setBodyId();&nbsp;\n\n<\/code><\/div>\n\n<p>Finally, if the $bodyId variable is not empty, add the id attribute on the body tag:<\/p>\n<div class=\"codeblock\"><code>\n&lt;body&lt;?php&nbsp;if(!empty($bodyId))&nbsp;echo&nbsp;'&nbsp;id=\"'.$bodyId.'\"';?&gt;&gt;&nbsp;\n\n<\/code><\/div>\n\n<h2>Conclusion<\/h2>\n<p>It&rsquo;s so simple, yet powerful. This could also easily be recoded in other programming languages. What do you think? Any ideas for improvement?<\/p>","14":{"old_id":{}}}}