Pre 4th of July dinner: ribs, chili, baked beans, watermelon....mmmm

Set a Body Id Using PHP

One of the first things I do when I am creating the markup for a new site, is to set a body id. You may wonder what I mean when I say “set a body id”. What I mean is to dynamically check the url to figure out which section you are in. This tutorial will show how to do this dynamically using PHP, and also how to integrate it into WordPress.

Why Should I Set a Body Id?

There are plenty of reasons why you should, here are a few:

  • Maybe your design has different colors depending upon which section you are in. Instead of having to touch the markup, you can just modify the CSS depending upon the id on the body.
  • You can control the current states for your navigation.
  • Maybe the markup on your homepage is a little different than subpages, so instead of creating a different template, just stick in an if statement.

Setting Up the Code

So typically, you setup your navigation to match your directory structure. Ex: Top level navigation is about, and there is a folder on the root called about. So the easiest thing to do, is just check the url and determine which section you are in. This is the code that sets the body id on my site:

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

    if(!isset($bodyId)) {
		if(eregi('^/about/',$path) == 1) {
			$bodyId = 'about';
		} else if(eregi('^/blog/',$path) == 1) {
			$bodyId = 'blog';
		} else if(eregi('^/contact/',$path) == 1) {
			$bodyId = 'contact';
		} else if(eregi('^/work/',$path) == 1) {
			$bodyId = 'work';
		} else if(eregi('^/play/',$path) == 1) {
			$bodyId = 'play';
		} else if ($path == '') {
			$bodyId = 'home';
		} else {
			$bodyId = 'general';
		}
	}

    return $bodyId;
}
?>

Sure, you could do this dynamically and pull in the top level folder from the url, but I have found there are too many situations that arise where you want multiple sections to have the same body id, or you want to set other variables section by section. So I stick with this method, and it has been successful.

My Example

My example is going to be a little different because it is in a subsection of my site. So here is the code I am using to control setting the body id in the example:

<?php
function exampleSetBodyId() {
    $path = $_SERVER['REQUEST_URI'];

    if(!isset($bodyId)) {
		if(eregi('^/play/set-a-body-id/about/',$path) == 1) {
			$bodyId = 'about';
		} else if(eregi('^/play/set-a-body-id/blog/',$path) == 1) {
			$bodyId = 'blog';
		} else if(eregi('^/play/set-a-body-id/contact/',$path) == 1) {
			$bodyId = 'contact';
		} else if(eregi('^/play/set-a-body-id/work/',$path) == 1) {
			$bodyId = 'work';
		} else if(eregi('^/play/set-a-body-id/play/',$path) == 1) {
			$bodyId = 'play';
		} else if ($path == '/play/set-a-body-id/') {
			$bodyId = 'home';
		} else {
			$bodyId = 'general';
		}
	}

    return $bodyId;
}
$bodyId = exampleSetBodyId();
?>

So in the $bodyId variable, you have the value of the body id, so just print the variable on the body tag:

<body id="<?=$bodyId; ?>">

Some Practical Uses

As I discussed at the beginning of the post, there are a lot of benefits to having a body id set on every page. This is the demo section that I am discussing below.

Different Colors Per Section

If you click through the navigation in the example, you can see the colors are different for each section. This can be easily accomplished without changing any markup through the power of descendant selectors. Here is the part of the CSS that is controlling the color of the borders:

div#content { border: 1px solid #000; }
ul#nav { border-top: 1px solid #000; }
body#home div#content, body#home ul#nav { border-color: #FF6600; }
body#about div#content, body#about ul#nav { border-color: #429C19; }
body#blog div#content, body#blog ul#nav { border-color: #54D0ED; }
body#work div#content, body#work ul#nav { border-color: #A81919; }
body#play div#content, body#play ul#nav { border-color: #400152; }
body#contact div#content, body#contact ul#nav { border-color: #F8DC0C; }

Here is the part that is changing the color of the h1:

body#home h1 { color: #FF6600; }
body#about h1, { color: #429C19; }
body#blog h1 { color: #54D0ED; }
body#work h1 { color: #A81919; }
body#play h1 { color: #400152; }
body#contact h1 { color: #F8DC0C; }

Obviously this is not the most beautiful example, but hopefully the idea makes sense.

Current State on Navigation

There are different ways to set the current state on the navigation, but by assigning an id to each navigation element, you can use descendant selectors again. Here is the markup:

<ul id="nav">
	<li id="homeNav"><a href="/play/set-a-body-id/">Home</a></li>
	<li id="aboutNav"><a href="/play/set-a-body-id/about/">About</a></li>
	<li id="blogNav"><a href="/play/set-a-body-id/blog/">Blog</a></li>
	<li id="workNav"><a href="/play/set-a-body-id/work/">Work</a></li>
	<li id="playNav"><a href="/play/set-a-body-id/play/">Play</a></li>
	<li id="contactNav"><a href="/play/set-a-body-id/contact/">Contact</a></li>
</ul>

Then, we use the following CSS to change the background color and text color when we are in that section:

body#home ul#nav li#homeNav a { background: #FF6600; }
body#about ul#nav li#aboutNav a { background: #429C19; }
body#blog ul#nav li#blogNav a { background: #54D0ED; }
body#work ul#nav li#workNav a { background: #A81919; }
body#play ul#nav li#playNav a { background: #400152; }
body#contact ul#nav li#contactNav a { background: #F8DC0C; }
body#home ul#nav li#homeNav a, body#about ul#nav li#aboutNav a, body#blog ul#nav li#blogNav a, body#contact ul#nav li#contactNav a { color: #000; }
body#work ul#nav li#workNav a, body#play ul#nav li#playNav a { color: #fff; }

Slightly Different Homepage Markup

Typically the markup for homepages are slightly different. But, if you are using one header and footer template for the entire site, you probably don’t want to create another template just for the homepage. So since we have the body id that tells us when we are on the homepage, we can just write a simple if statement:

<?php if($bodyId == 'home') { ?>
	…PUT YOUR HOMEPAGE SPECIFIC ELEMENTS HERE…
<?php } ?>

Make it Work with WordPress

So just take the setBodyId function that we defined earlier, and add it to your WordPress theme functions (functions.php).

After you have added the function, we want to add actions to wp_head and wp_footer (for some reason there isn’t a WordPress Hook Reference for wp_footer, but it is essentially the same as wp_head, just in the footer). Here is how we add our function to those hooks:

add_action('wp_head', 'setBodyId');
add_action('wp_footer', 'setBodyId');

Then, in your header, just call the wp_head hook, and call our function:

<?php wp_head(); $bodyId = setBodyId(); ?>

There you have it, you have the body id defined in the $bodyId variable, and you can do with it what you want.

Other Thoughts

I think by setting an id (or class) on such a high level element gives you a lot of control over its descendants. Another interesting idea that I heard was to use jQuery to determine the browser and version that the user is using, then add a class on the body. That way you could differ your CSS depending on which class is on the body. That idea would eliminate the need for conditional comments (at least for users with JavaScript enabled).

So hopefully this tutorial shows you an easy way to make some site-wide tasks simpler, and I am interested to see if other people have ideas for what to do with body ids.

Share This:
  • del.icio.us
  • Digg
  • Twitter
  • Facebook
  • StumbleUpon
  • Google Bookmarks
  • NewsVine
  • Technorati
  • Reddit
  • Design Float
  • LinkedIn

RSS feed of comments for this entry

  1. Body IDs can be absolute lifesavers, I’ll certainly attest to that.

    Just a few notes on the PHP side…

    You could get away with just using stripos checks against the URI rather than ereg. If you do feel the need to use regular expressions (i.e. for more complicated URI-matching), then you’d do well to replace eregi with the pcre-compatible preg_match function (see http://php.net/pcre), which is faster and not prone to being discontinued any time soon (ereg will not be in the PHP core as of PHP6).

  2. @Mark-
    Nice, thanks for the PHP tips.

  3. Yet another code snippet killed by WP :)
    If you’re posting code, consider using plugins such as iG Syntax Hiliter. Otherwise, all we get is curly quotes that crash code :)

  4. @Ozh, I implemented this on a Wordpress site we just built and it worked fine. I did take into account what Mark said and use preg_match instead. It worked great and even does away with the true/false check, it looks something like this:

    function setBodyId() {
        	$path = $_SERVER['REQUEST_URI'];
    	if(!isset($bodyId)) {
    		if (preg_match('/about/i',$path)) {
    			$bodyId = 'about';
    		} else if (preg_match('/contact/i',$path)) {
    			$bodyId = 'contact';
    		} else if (preg_match('/services/i',$path)) {
    			$bodyId = 'services';
    		} else if (preg_match('//i',$path)) {
    			$bodyId = 'home';
            	} else {
                    	$bodyId = 'general';
            	}
            }
        return $bodyId;
    }
    $bodyId = setBodyId();
  5. thanks! great implementation! just what i needed.

  6. Hi Trevor,
    I migrated this asp site over to php because of my web server.
    the navigation on the left uses conditional asp statement to change the css link behaviour depending on the page you are on.
    could you help me implement the php code?

    you can view the two behaviours on the original site:
    http://www.toolgal.com/chain.asp
    and the migrated site:
    http://www.dmdesign.co.il/toolgal/chain.php

    I would be glad to send you the source codes if needed.

    Thanks,
    Dan

  7. @Dan-
    Without looking at the actual ASP, I am assuming that it may be just checking the URL to decide what to do with the navigation.

    You should be able to examine the URL and use conditionals to determine what to do.

    Hopefully that should help.

  8. BodyId’s & are MUSTS for serious site developers with growing content, especially if your content is driven by a database.

    For those that don’t like or you can change the following for a cleaner look:

    Home
    About

    The CSS will change a little too:

    body#home #nav #home a { styles... }
    body#about #nav #about a {styles... }
    
    .subnav { ...
    .subnav a:link { ...
    .subnav a:hover { ...

    //just a note for the newbs like me

    • 5.14.2008 at 8:45 am
    • #

Speak Your Mind

* Denotes Required Field

  1. Sick of filling out this form? Register or Log in now.
  2. To post code snippets, use <pre><code>YOUR CODE HERE</code></pre>
Me, Trevor Davis. My blue steel face…

Hi, I’m Trevor Davis

I’m a 25 year old Front-End Developer living in Alexandria, VA. I work full-time at Matrix Group International and freelance on the side.

I specialize in CSS, HTML, jQuery & WordPress. See more of my work, and then hire me.

Recent Work

  • Monica Davis
  • The National Christmas Tree
  • Matrix Group International
  • The MatriX Files
  • Wireless Career
  • George Washington Wired
  • Direct Selling 411
  • Makeup Bizz
  • InstallNET
  • National Park Foundation
  • Worldwide Breast Cancer
  • Food Marketing Institute
See More of My Work

Asides