Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I have wondered about the web and came across this beautiful piece of code:

if(has_post_thumbnail()){ 

the_post_thumbnail();  

}else{ 

  echo '<img src="' .  get_bloginfo('template_directory') . '/images/default_post_thumb.jpg" />';

}

What it does, is adds a default thumbnail to every single post. That's good for a portfolio blog, but what if I have loads of categories, e.g. one category is tutorials and another is music - I must have different default thumbnails for those categories.

Can anybody please explain to me how I can customize this code to show different default thumbnails for different categories?

Thanks :)

share|improve this question

1 Answer 1

up vote 2 down vote accepted

The code below shows the "post-thumbnail" aka the featured image if the post has one, if not depending on the category, the default thumbnail is shown (with the comments, the code should be self-explanatory):

<?php

// If the post has a featured image defined use it
if( has_post_thumbnail() ) {
    the_post_thumbnail();

// Default image for Technology category
} elseif ( is_category( 'technology' ) ) {
    echo '<img src="' .  get_bloginfo('template_directory') . '/images/default_technology_post_thumb.jpg" />';

// Default image for Gadgets category
} elseif ( is_category( 'gadgets' ) ) {
    echo '<img src="' .  get_bloginfo('template_directory') . '/images/default_gadgets_post_thumb.jpg" />';

// Default image for all others
} else {
    echo '<img src="' .  get_bloginfo('template_directory') . '/images/default_post_thumb.jpg" />';
}

?>

Suggested Reading: WordPress Codex — Conditional Tags

share|improve this answer
    
Do I put this in functions.php? –  Nick Jul 1 '12 at 10:38
    
@Nick Then mark it as the answer :) –  its_me Jul 1 '12 at 10:38
    
No, it doesn't go into the theme's functions.php. You need to add it in your template files (index.php, archive.php, search.php, content.php, or single.php, etc.) depending on where you want the thumbnail to be shown. –  its_me Jul 1 '12 at 10:41
    
ok. I'll try that. By the way, does it matter where I put above code in page.php/index.php? –  Nick Jul 1 '12 at 10:42
    
Yes. In general, code in index.php shows on homepage, archive.php on archive pages (category & tag archives), search.php on search results pages, single.php in posts, and so on. So yes, where you add the code matters. –  its_me Jul 1 '12 at 10:51

Your Answer

 
discard

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.