Typominima, free typography based minimal WordPress theme

WordPress How To: Latest Posts by Category Archive

WordPress - Latest posts by categoryOne technique that is most common with WordPress magazine or news style themes is the display of an archive of the latest posts by category, as simple titles or with post excerpts. This is useful for the previously mentioned theme styles, but not only. It can be used to set up custom blog homepages, 404 pages, landing pages or even a special archive page.

This tutorial will help you build a ‘Latest Posts by Category Archive‘ in a very easy way. The widths in the CSS styling presented below have been calculated based on the default WordPress theme, assuming that is the most common theme available to anyone.

If you are looking for a plugin to generate such an archive, please check out: WP Plugin: Latest Posts by Category Archive.

Setting up the page template

Open up you favorite code editor and create a blank document. Save the document as ‘category-archive.php’ (or any other name you’d prefer) in the default WordPress theme directory (wp-content/themes/default).

The first step is to asign our new template a name and a page-like structure, so based on the default theme’s page template, the code you should paste in your new document is:

<?php
/*
Template Name: Category Archive
*/
?>

<?php get_header(); ?>

<div id="content" class="narrowcolumn">

	<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
	<div class="post" id="post-<?php the_ID(); ?>">
	<h2><?php the_title(); ?></h2>
		<div class="entry">
			<?php the_content('<p class="serif">Read the rest of this page &raquo;</p>'); ?>

			<?php wp_link_pages(array('before' => '<p><strong>Pages:</strong> ', 'after' => '</p>', 'next_or_number' => 'number')); ?>

		</div>
	</div>
	<?php endwhile; endif; ?>

	<!-- Category Archive Start -->
	<!-- Category Archive End -->

</div>

<?php get_sidebar(); ?>

<?php get_footer(); ?>

The template above will make sure to display the page name you set up, and also, any additional content you might want to add before the archive, from you WordPress page editor. We will be adding our ‘latest posts by category’ code between the ‘Category Archive Start’ and ‘Category Archive End’ comments.

Adding the archive’s PHP code

Simply put, the code below will cycle through the first-level categories of your blog (parent categories), check for the ones that are not empty and if this condition is met, return an unordered list of the latest 5 post from each category. Empty categories will not be displayed.

<?php
/*
Template Name: Category Archive
*/
?>

<?php get_header(); ?>

<div id="content" class="narrowcolumn">

	<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
	<div class="post" id="post-<?php the_ID(); ?>">
	<h2><?php the_title(); ?></h2>
		<div class="entry">
			<?php the_content('<p class="serif">Read the rest of this page &raquo;</p>'); ?>

			<?php wp_link_pages(array('before' => '<p><strong>Pages:</strong> ', 'after' => '</p>', 'next_or_number' => 'number')); ?>

		</div>
	</div>
	<?php endwhile; endif; ?>

	<!-- Category Archive Start -->
	<ul class="catArchive">
	<?php
	$catQuery = $wpdb->get_results("SELECT * FROM $wpdb->terms AS wterms INNER JOIN $wpdb->term_taxonomy AS wtaxonomy ON ( wterms.term_id = wtaxonomy.term_id ) WHERE wtaxonomy.taxonomy = 'category' AND wtaxonomy.parent = 0 AND wtaxonomy.count > 0");

	$catCounter = 0;

	foreach ($catQuery as $category) {
			
		$catCounter++;

		$catStyle = '';
		if (is_int($catCounter / 2)) $catStyle = ' class="catAlt"';

		$catLink = get_category_link($category->term_id);

		echo '<li'.$catStyle.'><h3><a href="'.$catLink.'" title="'.$category->name.'">'.$category->name.'</a></h3>';
			echo '<ul>';

			query_posts('cat='.$category->term_id.'&showposts=5');?>

			<?php while (have_posts()) : the_post(); ?>
				<li><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></li>
			<?php endwhile; ?>

				<li><a href="<?php echo $catLink; ?>" title="<?php echo $category->name; ?>">More <strong><?php echo $category->name; ?></strong></a></li>
			</ul>
		</li>
		<?php }	?>
	</ul>
	<!-- Category Archive End -->

</div>

<?php get_sidebar(); ?>

<?php get_footer(); ?>

You should now save your file, because we’re done editing it. As you can see, the archive code has been added between the ‘Start’ and ‘End’ comments. Now let’s go through the code and dissect it.

The PHP code explained

The first thing we do is to set up a database query to cycle through the non-empty parent categories:

$catQuery = $wpdb->get_results("SELECT * FROM $wpdb->terms AS wterms INNER JOIN $wpdb->term_taxonomy AS wtaxonomy ON ( wterms.term_id = wtaxonomy.term_id ) WHERE wtaxonomy.taxonomy = 'category' AND wtaxonomy.parent = 0 AND wtaxonomy.count > 0");

You can further tweak this query to exclude categories or specify categories to be listed based on their ID, with the use of the MySQL comparison functions NOT IN or IN.

Let’s say that you’d like the archive to exclude the categories with IDs 2, 5 and 6. Your query would become:

$catQuery = $wpdb->get_results("SELECT * FROM $wpdb->terms AS wterms INNER JOIN $wpdb->term_taxonomy AS wtaxonomy ON ( wterms.term_id = wtaxonomy.term_id ) WHERE wtaxonomy.taxonomy = 'category' AND wtaxonomy.parent = 0 AND wtaxonomy.count > 0 AND wterms.term_id NOT IN (2,5,6)");

Similarly, if you want to display only the categories with IDs 2,5 and 6, you’d have:

$catQuery = $wpdb->get_results("SELECT * FROM $wpdb->terms AS wterms INNER JOIN $wpdb->term_taxonomy AS wtaxonomy ON ( wterms.term_id = wtaxonomy.term_id ) WHERE wtaxonomy.taxonomy = 'category' AND wtaxonomy.parent = 0 AND wtaxonomy.count > 0 AND wterms.term_id IN (2,5,6)");

For further help with comparison operators and functions, you can check out the MySQL manual.

Next, we set up a category counter which will be incremented each time a category will be displayed. Based on this counter, the code adds a ‘catAlt‘ class that you can use to style differently consecutive categories. In our case, we’ll use it to shift the categories into two columns. This is were the alternate classes are assigned:

$catCounter++;

$catStyle = '';
if (is_int($catCounter / 2)) $catStyle = ' class="catAlt"';

The category list is built by the use of foreach and it helps retrieve vital information about the categories, such as name and permalink:

foreach ($catQuery as $category) {
	/* Code used to retrieve and display the latest posts */
}

After we display the category title and link through this line of code

echo '<li'.$catStyle.'><h3><a href="'.get_category_link($category->term_id).'" title="'.$category->name.'">'.$category->name.'</a></h3>';

we continue by using a custom query to retrieve the latest 5 posts from the current category in the cycle, followed by a link to the complete category archive:

query_posts('cat='.$category->term_id.'&showposts=5');?>

<?php while (have_posts()) : the_post(); ?>
	<li><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
	<li><a href="<?php echo $catLink; ?>" title="<?php echo $category->name; ?>">More <strong><?php echo $category->name; ?></strong></a></li>

And that’s about everything in terms of coding! Now, onto the CSS styling.

Styling the archive

Find the style.css file in your default theme’s directory, open it and scroll down to the end of the file. Now copy the code below and paste it in your file.

/* Latest posts by category styles */

.catArchive {
	width: 450px;
	overflow: hidden;
	margin: 20px 0 0 0;
	padding: 0;
	list-style-type: none;
}

.catArchive h3 {
	font: normal bold 18px sans-serif;
	border-bottom: 1px solid #666;
	margin: 0;
	padding: 0 0 3px 0;
	display: block;
}

.catArchive li {
	display: block;
	float: left;
	width: 210px;
	margin: 0 30px 30px 0;
}

.catArchive ul {
	margin: 0;
	padding: 0;	
}

.catArchive li li {
	border-bottom: 1px solid #ddd;
	margin: 0;
	padding: 4px 0;
}

.catAlt {
	margin-right: 0 !important;
}

Now, save the file. We’re done!

Note: Keep in mind that column sizes have been calculated based on the available space (450 pixels) in the default theme’s content area. So, our columns should each be 210 pixels wide, with a 30 pixels spacing between them.

Since the column shifting is done with the help of float, I’ve set the overflow to hidden to stretch the list full height. This can only work with a fixed given container width, which in our case is 450px set on .catArchive.

If your new to “floating”, Sarah has posted a fairly easy to understand article about the float property on BloggingTips.com.

You can download an archive containing both source files: Download.

More Blogsessive Content