0

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.

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

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:

http://codex.wordpress.org/Function_Reference/body_class

Edit:

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.

  • 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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