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
- $categoryslug = the category slug of posts to display
- $incexcerpt = set to true or false if the post excerpt is to be included on the list.
- $numberposts = total posts to display – I used 9999 for an approximate infinity.
// 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.






