WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm designing a new theme and in my page template a have a section where an image is displayed . I would like this image to change depending on which page is loaded.

The section is a DIV like this: <DIV class="ximage"></DIV>

What I would like to do is to add a class to the DIV depending om page loaded and then style the class with background-image in CSS.

I know you can do this with for example body_class() if you want to add classes to BODY. But how do I do this with a DIV?

There will be quite a few pages in this theme, so ceate a template for each page seems wrong.

share|improve this question
Since each page has its own unique ID, just give the div a class made of a name along with this very ID (e.g., class="ximage page-<?php the_ID(); ?>"). – tfrommen Mar 10 '13 at 17:12
This looks promising. Will try. Thanks! – BoBoz Mar 10 '13 at 17:48
up vote 2 down vote accepted

You might want to consider using the Wordpress function body_class()

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

Then you could use the body class as your current page reference.

This function is for example used by the Twenty-Twelve theme.

For a single post it will become

<body class="single single-post ...">

and for the home page:

<body class="home blog ...">

You can read more about this function in the Codex here:



I know you can do this with for example body_class() if you want to add classes to BODY. But how do I do this with a DIV?

You could use it in your div tag:

<div <?php body_class(); ?>></div>

but it should be sufficient to have this only in the body tag.

share|improve this answer
But this is already in the BODY section. So adding a background-image in CSS to a class will also add same image to BODY? Or perhaps you can target the CSS? – BoBoz Mar 10 '13 at 17:54
You could try .home .ximage {background:...} and .single .ximage {background:...} – birgire Mar 10 '13 at 17:58
The whole purpose for the body_class() is so you can target elements in the css by a specific page. To try and add to it is overkill when it's already done for you. – Jacob Rambo Mar 10 '13 at 18:27
Got it! Thanks! – BoBoz Mar 10 '13 at 18:34

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.