I'm using the function wp_get_recent_posts to return the latest three posts on a page and I want to get them with their titles, categories, and a brief excerpt. When I look at the documentation on that function, I see that it returns an array of items, but it doesn't say what is available in that array to extract from, so I'm testing by guessing at the names (see this page) - my guess on the post_content was right.

For getting the category, I've tried $recent["category"], $recent["the_category"], and $recent["post_category"] and for the excerpt I've tried those as well, except replace category with excerpt. The code I'm using is below:

                    $args = array( 'numberposts' => '5' );
                    $recent_posts = wp_get_recent_posts( $args );
                    foreach( $recent_posts as $recent ){

                        echo '<h2><a href="' . get_permalink($recent["ID"]) . '">' .   $recent["post_title"].'</a></h2><h3>Posted in '. $recent["the_category"] .'</h3><p>'.$recent["post_content"].'</p>';


I would suggest using WP_Query() instead. Like so:

$category = 'whatever';
$new_query = new WP_Query(
        'post_type'         => 'post',
        'posts_per_page'    => -1,
        'category_name'     => $category;

if ($new_query->have_posts()) {
    $i = 0;
    while ($new_query->have_posts()) {
        $postid = get_the_ID();
        // Your output code.

Merely change $category to whatever you need. Make it an array() if you want to have several categories.
If however, you will be doing this for a custom post type, you need to use the tax_query array, like so:

'tax_query' => array(
        'taxonomy' => 'people',
        'field'    => 'slug',
        'terms'    => 'bob',

Above example is taken straight from the WordPress Codex.

  • So with this function, I can filter by category? Reading documentation, looks like $query = new WP_Query( array( 'category_name' => 'staff' ) );? – WashDCDev Dec 14 '16 at 16:53
  • @WashDCDev Yes that would work. If you use it for custom post type however, you'd need to use 'tax_query' which is a bit more complicated, but still easy imho. I'll amend my answer to include the category filtering. – Athoxx Dec 15 '16 at 7:40
  • @WashDCDev I have amended my answer with both the category and tax_query code. – Athoxx Dec 15 '16 at 10:52
  • Cool; excellent answer. – WashDCDev Dec 15 '16 at 14:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.