Display Posts From A Category In WordPress
Posted in WordPress | Posted on
01-25-2012 |
5 Comments
Tags: custom wordpress query, wordpress tricks
Recently I had a run in with coding with a client who had a developer put together a sloppy custom WordPress query in place of a proper loop. In fact, it was amazing because it was put in replace of code on a great premium theme by StudioPress. By the way, no it was not StudioPress who did it, so let me get that out of the way. They are good at what they do.
Anyhow, the custom query was three different pieces of code: a section to show to first 5 most recent posts, and then two columns underneath to show two different categories that the site owner wanted to feature. The was done using a similar solution to the one At Weblog Tools Collection called Define Your Own WordPress WP-Query.
The problem was that this solution was not providing a good pagination. The “Next” and “Previous” did not work, and even if I wanted to use my favorite WP-PageNavi plugin, then I was pretty much – “sorry, out of luck.” This does not work well as a replacement for the regular loop, especially for what it was being used as.
So, I set out to put together a better solution. In the end, I displayed the most recent posts by normal Loop means. For the categories, I used the following:
<?php $recent = new WP_Query(); ?>
<?php $recent->query('cat=1&showposts=3'); ?>
<?php while($recent->have_posts()) : $recent->the_post(); ?>
<h3><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></h3>
<div class="attachment-post-thumbnail">
<?php the_post_thumbnail(); ?>
</div><?php the_content_limit(130, ""); ?>
<?php endwhile; ?>
We are still using a custom WP_Query, but only using it for the categories. You can replace the 1 after cat=1 to whatever category you want to display, and you can change the number of posts displayed by changing the number in showposts=3.
You can customize the code further with CSS and adding other attributes.
I left some styling to include the thumbnail, title, and a short excerpt, even using the_content. However, you can change it to the_excerpt if you have set your excerpts through your functions.php or excerpt plugin. This code goes in your WordPress theme template where you want it, however I use this normally for the theme’s template file that is for the front page of the website. This is good for sites that are more magazine-like.
Sound easy?







