9 Ways to Set Dynamic Body IDs via PHP and WordPress
by Jeff Starr on Tuesday, May 26, 2009 – 35 Responses
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:..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()statementsFor 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
$pagevariable and then strips out everything except for the file name. The$pagevariable is then echoed as the ID attribute for the body element.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.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 forecho()for greater efficiency.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! :)
Method 5
Here is a more versatile method that I learned from Trevor Davis. 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
$pathvariable 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.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
$bodyIdvariable from Trevor’s script: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:Notice how this technique cleverly outputs the
post_namevariable 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, shows us how to expand the script and clean things up by placing it the
functions.phpfile: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:
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’s excellent Sandbox Theme for WordPress:
This code would then be followed by this line of code:
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:..you get something like this in your source-code output:
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! ;)
May as well learn all of it, we've gone this far...

No comments:
Post a Comment