This hack makes WordPress display a category image next to posts.

Every category needs to have an *.png image named in accordance to the “nice name” of the category (if the category is called “Web Development”, the nice name would be “web-development” so the category image should be “web-development.png” and placed in the /wp-images folder in the root of a WordPress blog).

A “my-hacks.php” file must exist on the server of a WordPress installation. If one does not exist create one. Also, ensure that the “Use legacy my-hacks.php file support” checkbox is checked in Options > Miscellaneous in the admin area of wordpress.

Place the following code into a “my-hacks.php” file in the root of your WordPress blog.

function category_images($seperator = '', $image_type = 'png', $image_directory = '/wp-images/') {
    $categories = get_the_category();
        $image_directory = preg_replace('|/+$|', '', $image_directory);
    if ('' == $seperator) {
                echo '<span>';
                foreach ($categories as $category) {
                        $category->cat_name = stripslashes($category->cat_name);
                        echo "<a href='" . get_category_link(0, $category->category_id, $category->category_nicename) . "' title='View all posts in $category->cat_name'><img src='$image_directory/$category->category_nicename.$image_type' alt='$category->cat_name' /></a>";
                }
                echo "\n</span>";
    } else {
                $i = 0;
                foreach ($categories as $category) {
                        $category->cat_name = stripslashes($category->cat_name);
                        if (0 < $i) echo $seperator . ' ';
                        echo "<a href='" . get_category_link(0, $category->category_id, $category->category_nicename) . "' title='View all posts in $category->cat_name'><img src='$image_directory/$category->category_nicename.$image_type' alt='$category->cat_name' /></a>";
                }
                ++$i;
        }
}

To display category images place the following function in your loop:

<?php
category_images(' ');  ?>
  • Dwaynne

    Great tute, but could you explain what the code does? I am really enjoying the resouces on the blog, but I find that they aren’t as clear or step-by-step as they could be.

  • Dwaynne

    Just to clarify my previous comment: explain what each part of the code does in my-hacks.php

  • Prabin Kumar Sahu

    very nice article…. its really helpful… thnx