Attention Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

User:Esmi/ Changing Headers with body class()

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>

And your current CSS for the header looks like:

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

In header.php, replace:



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

Then change your CSS to:

#header {
	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);}

Classes Available

  • rtl
  • home
  • blog
  • archive
  • date
  • search
  • paged
  • attachment
  • error404
  • single (only available in 3.0)
  • single-{post_id}
  • postid-{post_id} (only available in 3.0)
  • attachmentid-{post_id}
  • attachment-{mime_type}
  • author
  • author-{user_nicename}
  • category
  • category-{category_slug}
  • tag
  • tag-{tag_slug}
  • page
  • page-id-{page_id}
  • page-parent
  • page-child
  • parent-pageid-{parent_id}
  • page-template
  • page-template-{page_template}-php
  • 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}