One problem I have come a cross lots of times is that I need to customize the WordPress loop, in other words I’d like to display posts from certain categories on the front page instead of the default one who shows the most recent posts in a descending order.
This is most convenient when you have a category where you post short links or snippets that you want to show in the sidebar or on the top of the page. Much like what the asides plugin do
. But I like to do things my own way so I’m gonna show you how to do this in a very easy way.
Create a category
Let’s start by adding a category, I have for example the category “WordPress tricks” which this post is filed under. Here I post tutorials and tips for WordPress and I’m gonna display the heading with a link to the posts in the sidebar
.
Adding posts
Go ahead and add some posts to your newly created category and make add the appropriate tags and if you want the posts to be filed under multiple categories thats no problem.
The code
To make the category heading appear in the sidebar we need to make a custom loop where we only want to retrieve and display the posts from our category. What you need to do is check what id your new category has, mine has the ID 17 . You can check this on the categories page in WordPress admin.
Let’s start by getting the 5 most recent posts from the category with ID 17 in an ascending order. If you want a descending order substitute the “ASC” with DESC in the code below. Add this somewhere in your sidebar.php or on which ever template file you wish.
$posts = query_posts("cat=17&showposts=5&order=ASC");
So now the variable “posts” contain our posts with all the meta data and attributes associated with a post. Now all we have to loop through all the posts and display the heading with a link and perhaps the date.
The loop
Add this to where you want the posts to appear in your sidebar
shown broad spectrum efficacy in a majority of patients generic viagra online for sale desire, although ED may occur concurrently with these.
. Check the comments in the code for explanations.
Now we have a nice ordered list with the title of the post with a link with the date. On my test sidebar it looks like this: