Changing Headers with WordPress body_class()

Posted on Friday, August 7th, 2009 at 12:39 pm in

WordPress 2.8 introduced a new function — body_class() — that attaches a list of classes to the <body> element according to what type of page is being displayed. These classes can be used — in conjunction with your theme’s stylesheet — to display different headers on different page types.

Let’s assume your header markup looks something like:

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

<div id="header">
<div id="headerimg">
<h1><a href="<?php bloginfo('url'); ?>"><?php bloginfo('name'); ?></a></h1>
<div class="description"><?php bloginfo('description'); ?></div>
</div>
</div>

And your current CSS for the header looks like:

#header {background: #73a0c5 url(images/header.jpg) no-repeat left top;}

Replace:

<body>

with

<body <?php if (function_exists('body_class')) body_class(); ?>>

in header.php. Then change your CSS to:

#header {
	background-color:#73a0c5;
	background-image:url(images/header.jpg;
	background_repeat:no-repeat;
	background-position:left top;
}

You can now start applying different headers to different page types. Want a different header for categories? Use:

body.category #header url{background-image:url(images/header2.jpg;}

Want a different header for Fred’s author page? Assuming Fred logs in with the username ‘fred’, use:

body.author-fred #header url{background-image:url(images/header3.jpg;}

How about a different header for the category ‘Wibble’ (slug: wibble)?

body.category-wibble #header url{background-image:url(images/header4.jpg;}

Additional Classes

  • 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)

Just keep in mind that this approach will only work with WordPress 2.8 or above.

You might also be interested in

WordPress Installation and Set Up

Top