Celebrating 20 years online :)
Web Dev + WordPress + Security

9 Ways to Set Dynamic Body IDs via PHP and WordPress

When designing sites, it is often useful to identify different pages by adding an ID attribute to the <body> element. Commonly, the name of the page is used as the attribute value, for example:

<body id="about">

In this case, “about” would be the body ID for the “About” page, which would be named something like “about.php”. Likewise, other pages would have unique IDs as well, for example:

<body id="archive">
<body id="contact">
<body id="subscribe">
<body id="portfolio">

..again, with each ID associated with the name of the page. This identification strategy is useful for a variety of reasons, including the following:

  • Page-specific control over CSS via descendant selectors
  • Page-specific DOM manipulation via JavaScript
  • Page-specific control over the navigational interface, current-page highlighting et al
  • Page-specific content-inclusion via conditional PHP if() statements

For page-specific control over your design, using the current page name as the body ID will certainly do the trick. The question is, what is the best way to go about defining the different attributes? For static sites or for sites with only a few pages, it might be easiest to just add the IDs manually. For larger, dynamic sites, however, you can automate the process with the magical powers of PHP.

The basic idea is simple: use PHP to dynamically check the URL, extract the file name, and echo the name as the body ID for that specific page. The cool thing is that, once the page name is captured as a PHP variable, it can be tested conditionally to include or exclude page-specific content. This is a great way to consolidate and streamline content into a single file.

There are probably a million different ways to accomplish this sort of functionality, but I am only familiar with about nine different techniques, which actually do pretty much the same basic thing only in different ways. Even so, I apply body IDs for page-specific CSS styling all the time, and have refined my collection of PHP snippets to include the following nine ways of getting it done. Enjoy!

Method 1

This method captures the requested URI as a $page variable and then strips out everything except for the file name. The $page variable is then echoed as the ID attribute for the body element.

$page = $_SERVER['REQUEST_URI']; 
$page = str_replace('/', '', $page); 
$page = str_replace('.php', '', $page); 
$page = str_replace('?s=', '', $page); 
$page = $page ? $page : 'default'; 

<body id="<?php echo $page ?>">

Method 2

This variation streamlines the syntax of the previous method by using an array for the str_replace() function. I’m sure there is an even more efficient way of writing this, so speak up if you happen to know of one.

$page = str_replace(array('/', '.php', '?s='), '', $_SERVER['REQUEST_URI']); 
$page = $page ? $page : 'default'; 

<body id="<?php echo $page ?>">

Method 3

This method cuts to the chase by echoing the name of the PHP file directly (after removing the “.php” extension). I use this technique in my dark n’ minimalist Perishable theme (opens new tab). Note the convenient shortcut syntax for echo() for greater efficiency.

<body id="<?=basename($_SERVER['PHP_SELF'],'.php')?>">

Method 4

If I remember correctly, I discovered this technique from one of Chris Coyier’s excellent screencasts. I had to squint hard and type fast to catch it, but the code works great and I love having it at my disposal. The cool thing about this technique is that it echoes the name of the first-level directory and discards any subsequent directory information. Thanks Chris! :)

$url = explode('/', $_SERVER['REQUEST_URI']); 
$dir = $url[1] ? $url[1] : 'home'; 

<body id="<?php echo $dir ?>">

Method 5

Here is a more versatile method that I learned from Trevor Davis (404 link removed 2017/01/16). The benefit of this technique is that it enables you to specify the same body ID for multiple pages. The script captures the requested URI as a $path variable and then pattern-matches against user-defined character strings to determine its value. You could even adapt this script to set variables according to an entire range of pages.

function setBodyId() {

    $path = $_SERVER['REQUEST_URI'];

    if(!isset($bodyId)) {

		if(eregi('^/about/', $path) == 1) {

			$bodyId = 'about';

		} elseif(eregi('^/archive/', $path) == 1) {

			$bodyId = 'archive';

		} elseif(eregi('^/contact/', $path) == 1) {

			$bodyId = 'contact';

		} elseif(eregi('^/business/', $path) == 1) {

			$bodyId = 'business';

		} elseif(eregi('^/pleasure/', $path) == 1) {

			$bodyId = 'pleasure';

		} elseif ($path == '') {

			$bodyId = 'home';

		} else {

			$bodyId = 'default';
	return $bodyId;
$bodyId = SetBodyId();

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

Earlier I discussed the idea of using the page-specific body ID to include conditional content. Here we may see an example of this technique by using the $bodyId variable from Trevor’s script:

<?php if($bodyId == 'home') {

// content placed here will only appear on the home page

} ?>

Method 6: WordPress

Moving on to WordPress-specific methods, here is a technique that Elliot Jay Stocks adapted from Darren Hoyt. The idea here is to take advantage of WordPress’ conditional tags in order to output the desired <body> ID:

<?php if (is_home()) { ?>

	<body id="home">

<?php } elseif (is_archive) { ?>

	<body id="archive">

<?php } else { ?>

	<body class="<?php echo $post->post_name; ?>">

<?php } ?>

Notice how this technique cleverly outputs the post_name variable for pages without an ID. This method certainly is useful, and there is much more that may be done with it.

Method 7: WordPress

Taking the conditional-tag method further, here is how to expand the script and clean things up by placing it the functions.php file:

<?php // dynamic body IDs

function dynamicBodyID() {

	if (is_home()) {

		echo ' id="home"';

	} elseif (is_single()) {

		echo ' id="single"';

	} elseif (is_search()) {

		echo ' id="search"';

	} elseif (is_archive()) {

		echo ' id="archive"';

This function is then called via the following code placed in your theme template:

<body<?php dynamicBodyID(); ?>>

Then, as with method #6, we may modify this technique to add a post-specific class to every single post page:

<?php // dynamic body IDs

function mytheme_body_control() {

	global $post; 
	$postclass = $post->post_name;
	if (is_home()) {

		echo ' id="home"';

	} elseif (is_single()) {

		echo ' id="single" class="'.$postclass.'"';

	} elseif (is_search()) {

		echo ' id="search"';

	} elseif (is_archive()) {

		echo ' id="archive"';

And once again, this function is then called via the following code placed in your theme template:

<body<?php dynamicBodyID(); ?>>

Method 8: WordPress

Here is a WordPress method that echoes the name of the parent page as the <body> ID, regardless of whether or not the page is a sub-page (or child-page). As we have seen, we can echo the name of any post or page via the following code:

<body id="<?php echo $post->post_name; ?>">

However, for pages that are children of parent pages, this snippet will echo the name of the child page instead of the name of the parent page, which may be more useful for the purposes of CSS styling. Fortunately, we may find a solution for this via plaintxt.org’s (404 link removed 2014/10/28) excellent Sandbox Theme for WordPress (404 link removed 2013/07/10):

	$current_page = $post->ID;
	$parent = 1;

	while($parent) {
		$page_query = $wpdb->get_row("SELECT post_name, post_parent FROM $wpdb->posts WHERE ID = '$current_page'");
		$parent = $current_page = $page_query->post_parent;
		if(!$parent) $parent_name = $page_query->post_name;

This code would then be followed by this line of code:

<body id="<?php echo (is_page()) ? "$parent_name" : ((is_home()) ? "blog" : ((is_search()) ? "other" : ((is_single()) ? "blog" : "blog"))); ?>">

That is all well and good for current versions of WordPress, but as we will see in the next example, the soon-to-be-released WordPress 2.8 includes a built-in method for applying page-specific body IDs that simplifies the process to the point of absurdity!

Method 9: WordPress

Those of you who keep up with the relentless evolution of WordPress certainly have heard about the new body_class() tag that is due out in version 2.8. As WPengineer points out, by simply including this in the <body> element:

<body <?php body_class(); ?>>

..you get something like this in your source-code output:

<body class="page-template page-template-tutorial-php logged-in">

Pure awesome-ness. Here is a list of the available classes for the new body_class() tag:

  • rtl
  • home
  • blog
  • archive
  • date
  • search
  • paged
  • attachment
  • error404
  • single postid-(id)
  • attachmentid-(id)
  • attachment-(mime-type)
  • author
  • author-(user_nicename)
  • category
  • category-(slug)
  • tag
  • tag-(slug)
  • page-parent
  • page-child parent-pageid-(id)
  • page-template page-template-(template file name)
  • search-results
  • search-no-results
  • logged-in
  • paged-(page number)
  • single-paged-(page number)
  • page-paged-(page number)
  • category-paged-(page number)
  • tag-paged-(page number)
  • date-paged-(page number)
  • author-paged-(page number)
  • search-paged-(page number)

Obligatory Hendrix Perm

The best part about running a personal, non-commercial blog such as Perishable Press is that I get to do and say whatever I want. I usually play it straight, sticking to the script and focusing on the topic at hand, but every now and then, I just gotsta exercise my right to cut loose and have a little fun. So today, instead of another boring and predictable article summary, I thought I would wrap things up with an obligatory nod to a song from my favorite band. Take that, sleepwalkers! ;)

About the Author
Jeff Starr = Designer. Developer. Producer. Writer. Editor. Etc.
Blackhole Pro: Trap bad bots in a virtual black hole.

29 responses to “9 Ways to Set Dynamic Body IDs via PHP and WordPress”

  1. Jeff Starr 2009/08/09 5:51 pm

    @Lewis Litanzios, That’s actually a great idea and something that I have been mulling over in my head regarding the best way to go about writing up a useful article. Thanks for the inspiration ;)

  2. Lewis Litanzios 2009/08/09 7:55 pm

    I ended up going 400+ lines deep into my post-template with the following:

    // controls body class background colours
    if ($pageID == 7 || $wp_query->post->post_parent == 7){
           $classes[] = 'fmcg';
    if ($pageID == 8 || $wp_query->post->post_parent == 8){
           $classes[] = 'corp';

    … but it’s a complete botch job :Z

    This subject really does need to be ironed out, cause there’s NOTHING online about it, let alone in the WP Codex for 2.8 yet.

    Most designers are raving about doing it all with CSS, but this isn’t what I call efficient:

    .category-advertising-corp{ background-color:#71919e;}
    .category-branding-strategy-design-corp{ background-color:#71919e;}
    .category-brochures-corp{ background-color:#71919e;}
    .category-core-creative-corp{ background-color:#71919e;}
    .category-events-corp{ background-color:#71919e;}
    .category-instore-corp{ background-color:#71919e;}
    .category-packaging-corp{ background-color:#71919e;}
    .category-web-new-media-corp{ background-color:#71919e;}

    Ta mate – let me know what you make of it (@ldexterldesign).

  3. Lewis Litanzios 2009/08/10 3:28 pm

    F*ck it:

    body[class*="fmcg"] #s
    body[class*="corp"] #s
    – A combination of CSS and greeeeeezy category naming to the rescue :]

    Do let me know if you get on with the body_class() conditional logic thing. I will stay tuned.


  4. Jeff Starr 2009/08/12 8:22 am

    Hi Lewis, I think there is a way to do this using PHP’s output buffering functionality. I will play around with it this weekend and try to get something posted soon.
    – Jeff

  5. Lewis Litanzios 2009/08/12 9:04 am

    Cool, rather you than me. Post up if you get something working.


  6. Jeff Starr 2009/08/16 8:51 pm

    @Lewis: Here you go:


    Thanks for the idea! :)

  7. thanks for the WP 2.8 body_class function, a real life saver!
    I enjoy reading your articles, they are always very well written and exhaustive.

    keep up the good work

    and this psychedelic background :-)

  8. Jeff Starr 2009/09/05 4:54 pm

    @paul: My pleasure! Thanks for the feedback :)

  9. Steve Coates 2009/10/04 9:06 pm

    Great article, thanks. Wasn’t aware of the new body_class() tag with WP2.8. I’ve used Sandbox for ages for the ease it allows with styling by adding all that goodness to the body tag.

    Nearly tempted to move to using the native wordpress tag but on experimentation it doesn’t add any category info (id or name) to the body tag on single posts which is a major limitation if you’re trying to style things based on category.

  10. Jeff Starr 2009/10/06 9:44 am

    @Steve: Yes, but there are always conditional tags to help with that. For example:

    <body<?php if(is_category('33')) { echo ' class="whatever"'; } ?>

    But I’ll admit, this method is a bit tedious and not as elegant. Have you checked out my body_class_plus() plugin?


    It is pretty flexible, and there may be a way to implement custom category classes.

  11. Steve Coates 2009/10/13 4:13 pm

    Thanks Jeff,

    WIll check it out.

  12. you are amazing. thank you for writing this.

Comments are closed for this post. Something to add? Let me know.
Perishable Press is operated by Jeff Starr, a professional web developer and book author with two decades of experience. Here you will find posts about web development, WordPress, security, and more »
Wizard’s SQL for WordPress: Over 300+ recipes! Check the Demo »
Crazy that we’re almost halfway thru 2024.
I live right next door to the absolute loudest car in town. And the owner loves to drive it.
8G Firewall now out of beta testing, ready for use on production sites.
It's all about that ad revenue baby.
Note to self: encrypting 500 GB of data on my iMac takes around 8 hours.
Getting back into things after a bit of a break. Currently 7° F outside. Chillz.
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.