Category Images Hack

April 15th, 2006, Published in Wordpress, 1,071 Views, Email This Email This

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(' ');
<< Include Preset Text In Wordpress Posts Separate Wordpress Category Feeds >>

Leave a Reply

Your e-mail will never be published.

Your Details

Your Comment