Automatically add a featured image

Is there a way to have a thumbnail image automatically added to a post when it is given a particular category?

For example, if I was to give a post a category ‘Music’, when it’s published it would automatically have a little thumbnail image of a guitar in the post without me having to do anything else.

How would I achieve this?

You can do that by following the instructions shown here.

Sounds like it’ll do the trick, thanks.

One more stupid question, is it just a case of wrapping that ‘foreach’ chunk of code in a function, dropping it into functions.php then calling it from within the relevant templates to get the image to display?

Sorry, i’m new to all this :slight_smile:

<?php
foreach((get_the_category()) as $category) {
    echo '<img src="http://example.com/images/' . $category->cat_ID . '.jpg" alt="' . $category->cat_name . '" />';
}
?>

This code you can put anywhere in any of your templates, wherever you want your image to appear. You don’t need to have it as a function in functions.php.

Pretend you’re putting your <img> element in your template like normal, but put that entire php code instead.

This…

$category->cat_ID . '.jpg"

…represents the image file name. So depending on the category id it will output something like 1234.jpg - so you would have your category image inside like:

http://examples.com/images/1234.jpg
alt="' . $category->cat_name . '"

This represents your alt tag and will use the category name in here.

You will want to be careful that you only have 1 category per post or you could have a number of images being displayed.

Excellent, thank you very much for the help.

Thanks for the link