PHP, Snippets, WordPress

Customising category.php in WordPress

I am using WordPress as a CMS for one of my websites. For that website, instead of having a default category page, I wanted to have a customised category page which lists titles of all posts under that category. And I also wanted to display a category image if it exists in /wp-content/uploads/images folder. And because there was no plugin which satisfies my requirements, I created a custom category.php file in my theme folder. Here's a snippet of my customised category.php.


<?php if (have_posts()) : ?>
<h2><?php single_cat_title(); ?></h2>
<?php
$current_category = single_cat_title("", false);
$image = '/wp-content/uploads/images/' . strtolower(str_replace(' ', '-', $current_category)) . '.jpg';
if (file_exists(ABSPATH . $image)) {
echo '<img src="' . get_bloginfo('url') . $image . '" alt="' . $current_category . '" />';
}
?>
<ol>
<?php while (have_posts()) : the_post(); ?>
<li>
<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>">
<?php the_title(); ?></a></li>
<?php endwhile; ?>
</ol>
<?php endif; ?>

What does the above code do?

1. Print out the title of current category
2. Assign the title of the category to a variable called current_category
3. Specify a relative file name for category specific image where image name is the title of the category in lower case with spaces being replaced by hyphens (-)
4. Check whether the specified image above exists on server
5. If it does, print out the image
6. In the post loop, print out titles of all posts under the current category in an ordered list with a link to the individual post page

[tags]wordpress, plugin, category.php, custom template[/tags]

5 thoughts on “Customising category.php in WordPress

  1. Holy ads, I put my adblocker to use today.

    you should also put your code into tags and format it.

  2. I also use wordpress, but i didn’t face any problem.

Comments are closed.

Twitter
LinkedIn
YouTube
Instagram