Wordpress coding

WordPress: Change background image based on post category

A client asked me to have a section of her WordPress website with a different look. In particular, a category (and all the posts inside it) should have a different background image.

The first thing I tried was installing a plugin named Background Manager, but I couldn’t activate it because the host didn’t support php 5.3. So, I decided to change the template’s code.

Let’s suppose that we want a different background image on a category with id=4. When loading a category page like www.site.com/?cat=4, you will notice that the body tag has the “category-4” class. In this way, it’s easy to edit the style.css file and add something like this:

background-image: url(‘url-to-background-file.png’);

This unfortunately doesn’t work with categories posts. For changing the background image for these posts too, we can use the WordPress function in_category, that check if the current post belong to a category. I opened the template’s header file (you can do it through the wp-admin interface or with an HTML editor) and I changed the body tag like this:

<body <?php if( in_category( 1 ) ) { ?> style=”background-image: url(‘url-to-background-file.png’);” <?php } ?> >

Ok, this isn’t the best way of doing it. First of all, we specify the background to use in two separate places (style.css for the category and header.php for the posts), making changes slower. A slightly better solution is to put our style in another css file that will be loaded only for the selected category and its posts, like this:

background-image: url(‘url-to-background-file.png’);

We can tell WordPress to load the stylesheet with the following code in the <HEAD> section of the header.php file:

<?php if( in_category(4) || is_category(4)) { ?>
<link rel=”stylesheet” href=”<?php bloginfo(‘template_url’)?>/style2.css” type=”text/css” media=”screen” />
<?php }

In this way, the css file with the custom body style will be loaded only if the category id equals 4, or if the post belongs to the that category.

Hope this helps!

Leave A Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.