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.
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?
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.