Listing posts by category in WordPress.

I recently wrote a function for wordpress to get posts by a certain category, which I thought I would share as it took ages to find enough information to write my own. This is useful for displaying certain posts on a page.

Add to functions.php

// Get Posts in a certain category
 function getPostsByCategory($categoryslug, $incexcerpt, $numberposts) {        
 global $post;
 $args = array(         
 'numberposts'     => $numberposts,
 'category_name' => $categoryslug,  
 'post_status'   => 'publish',
 'orderby'       => 'post_date',
 'order'         => 'DESC');
 $myposts = get_posts( $args );
 foreach( $myposts as $post ) :    setup_postdata($post);
 $excerptcontent = "";
 if ($incexcerpt == 'true') {
 $excerptcontent = '<br />' . get_the_excerpt();
 }
 echo '<li><a href="' . get_permalink() . '"><strong>' . get_the_title() . '</strong>' . $excerptcontent . '</a></li>';
 endforeach;
 if (count($myposts) == 0) {
 echo '<li>No posts found</li>';
 }
 }

Add to template or page.

This should be outside the loop.

<h2>Posts by category</h2> <ul> <?php getPostsByCategory('category-name', 'true', 9999); ?> </ul>

More information can be found in the WordPress Codex.

Posted August 17 2011 in Wordpress | No comments

No comments yet.

Leave a comment

Please note: * indicates a required field.

© Copyright Stuart Holmes 2006-2012. Some icon credits to Gentleface. Background from Subtle Patterns.

Blog Archive