imageupload

Reader Request – Use Category Slug Based Images for Posts

One of our VoodooPress readers had a question recently. Seems they were using the front end posting form we started talking about here. They became concerned that allowing users to upload new images for every post using this technique would soon fill their hosting allotment. That’s a valid concern. Let’s look at one possible technique here.

This reader wanted to have a category based image displayed for each post. That’s a fairly simple idea, just a few things to think through. First, we need to make sure that the code we use returns the category slug, not a link. We need to make sure that we only return one category slug too (or, if we want multiple category slugs, we need to loop through them to properly form our links – that’s a different tutorial).

First thing first, the setup. You’re going to need to create an image for each category, and name it exactly the same as your category slug. Make them all uniform size of course.

category_slug.png

And now, the code. This will go in whatever template you want to display the posts. If you already have the template set up to use featured images, great, this can just be edited on to the end of that. That way you can still assign featured images to each post individually from the backend if you like. If you do, it would be used… if not, we use the slug based images.

<?php
if( has_post_thumbnail() ) {
	the_post_thumbnail( 'thumb_id' );
}else{
	$category = get_the_category():
	$url = get_bloginfo( 'stylesheet_directory' );
	echo '<img src="' . $url . '/images/' . $category[0]->category_nicename . '.png" alt="' .$category[0]->cat_name . '" />';
}
?>

I think that is one approach that should work well. Uses the cat slug (We could also use the category ID by swapping category_nicename with cat_ID).

Leave a Reply