WordPress Looping through specific Category Tutorial
This tutorial will show you how to create a WordPress loop for getting posts from a specific category / categories. It’s similar to an archive page displaying a certain category, but by creating a custom loop there is more flexibility and customization options, especially when used in conjunction with custom page templates. A standard WordPress loop generally looks along the lines of this:
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>THE CONTENT<?php endwhile; else: ?><?php _e('No Results'); ?><?php endif; ?>The issue is in many scenarios you may want to include posts from one or a few categories. The archive feature of WordPress has the capabilities to display posts from a certain category, but it lacks flexibility so instead I prefer to create a custom loop using a page template.
The new loop is:
<?php if (have_posts()) : ?><?php$thePosts = get_posts('numberposts=50&category=1');foreach($thePosts as $post) :setup_postdata($post);?>THE CONTENT<?php endforeach; ?><?php else : ?>No Results<?php endif; ?>Assuming you use this loop with a custom page template you now have a way to loop through a certain category as well as the ability to make template customizations without having to modify the built in WordPress archives feature.
One last improvement…In my experience if you’re creating a custom loop like the one above you’ll probably be having more than one page with specific categories. That being the case, having a hard coded category ID is not efficient. Instead we can use a custom field to add some flexibility:
<?php$category = get_post_meta($post->ID, "category" true);$myPosts = get_posts('numberposts=50&category=' . $category. '');foreach($myPosts as $post) :setup_postdata($post);?>THE CONTENT<?php endforeach; ?><?php else : ?>No Results<?php endif; ?>When creating a new page you can choose your custom page template and will have the ability to loop through one or multiple categories by adding a custom field for “category”, then listing the category ID. In addition, if you wanted to add even more flexibility you could create a second post_meta option for limiting the number of posts that are displayed:
<?php$category = get_post_meta($post->ID, "category", true);$postLimit = get_post_meta($post->ID, "posts limit", true);$myPosts = get_posts('numberposts=' . $postLimit. '&category=' . $category. '');foreach($myPosts as $post) :setup_postdata($post);?>THE CONTENT<?php endforeach; ?><?php else : ?>No Results<?php endif; ?>Now you would add two custom fields, one for “category” and a second for “posts limit”. If you wanted to add more than one category for a page you would list out all the category IDs, seperating them with commas (EX: 1,2,3,4).
Just what I was looking for! I’m gonna try it out when I get home.
Thank you.
Adam Lawton
this wored great, thanks!