OK, I need some help on this.
I’ve adapted it, because it wasn’t doing what I wanted, plus the HTML wasn’t validating.
What I want is for an image to show on the home page for each category.
What I’ve got is a bunch of code that can be placed anywhere outside the Loop. It does what I want – mostly.
If there’s no image for a category, it echoes a default image.
If there IS an image for a category, it STILL echoes that default image. It’s not meant to. That’s where I’ve got stuck.
I THINK the line causing the problems is if( file_exists($image_path ."/images/". $image) )
I’ve checked by using echo $image_path."/images/".$image;
and that comes out fine with the url to the image.
Here’s the code, and below it is the output.
<?php
$image_path = get_bloginfo('stylesheet_directory');
$cats = get_categories();
$count=1;
foreach ((array)$cats as $cat) {
$catdesc = attribute_escape(strip_tags($cat->category_description));
$image = $cat->category_nicename .'.jpg';
if( file_exists($image_path ."/images/". $image) ) {
$cat_img = '<div class="category-image" id="cat-image-'.$count.'"'.'><a href="' . get_category_link($cat) . '" title="'. $catdesc .'"><img class="image-for-category" src="' . $image_path . '/images/' . $image . '" alt="' . $cat->cat_name . '" /></a></div>'."\n\n";
} else {
$cat_img = '<div class="category-image" id="cat-image-'.$count.'"'.'><a href="' . get_category_link($cat) . '" title="'. $catdesc .'"><img class="image-for-category" src="' . $image_path . '/images/default-category-image.jpg' . '" alt="' . $cat->cat_name . '" /></a></div>'."\n\n"; /*If no category image, display a default image called default-category-image.jpg*/
}
echo $cat_img ;
$count++;
}
?>
And here’s the output:
<div class="category-image" id="cat-image-1"><a href="https://www.mysite.com/index.php/category/fish/" title=""><img class="image-for-category" src="https://www.mysite.com/wp-content/themes/whatever/images/default-category-image.jpg" alt="fish" /></a></div>
<div class="category-image" id="cat-image-2"><a href="https://www.incenseheaven.com/there/index.php/category/elephants/" title=""><img class="image-for-category" src="https://www.incenseheaven.com/there/wp-content/themes/whatever/images/default-category-image.jpg" alt="elephant" /></a></div>
etc.