How to customize your WordPress category pages, an easier way

If you have the desire to customize your WordPress blog, and have attempted it, you surely know that it is a pain sometimes.

I was trying to cutomize my category pages to show the most recent post for that category, and only posts for that category.

  • Create a file called category.php in your theme’s directory.
    • This will default WordPress to use this page for categories from now on.
  • For showing only the most recent post with this category: Use this code:

<?php
get_header();
//the following gets an array of the categories for this post

$get_cat = get_the_category();

//the following will get the first category for your post and create a WordPress query that uses “The Loop” to show the most

// recent post from that category

$q = ‘cat=’.$get_cat[0]->cat_ID.’&showposts=1′;
$my_query = new WP_Query($q);
//the rest is just like everywhere else that you show posts on your blog

if($my_query->have_posts()){
while ($my_query->have_posts()) : $my_query->the_post();
?>
<h2>
<?php the_title(); ?>
</h2>
<?php
the_content(’Read the rest of this entry »’); ?>
<?php
endwhile;
}else{
?>
<h2 class=”center”>Not Found</h2>
<p class=”center”>Sorry, but you are looking for something that isn’t here.</p>
<?php
}

get_footer();
?>

  • For showing the only post with this category or showing the titles only if there are multiple posts: Use this code:

<?php
get_header();
$get_cat = get_the_category();
$q = ‘cat=’.$get_cat[0]->cat_ID.’&showposts=1′;
$my_query = new WP_Query($q);
if($my_query->have_posts()){
while ($my_query->have_posts()) : $my_query->the_post();
?>
<h2>
<?php the_title(); ?>
</h2>
<?php
//this is all I added to the previous one, it checks to see how many posts there are
if(count($posts) > 1){
the_content(’Read the rest of this entry »’);
}
?>

<?php
endwhile;
}else{
?>
<h2 class=”center”>Not Found</h2>
<p class=”center”>Sorry, but you are looking for something that isn’t here.</p>
<?php
}

get_footer();
?>

Now you can add the other normal wordpress template tags in these, just place them and try it out.

Note: The best Codex page I found for templating is here: The WordPress Loop

Sphere: Related Content

No Comments! Be The First!

Leave a Reply

27283 pages viewed, 126 today
8264 visits, 50 today
FireStats icon Powered by FireStats