Get Category and Excerpt From wp_get_recent_posts

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:

<?php
                    $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>';


                    }
                    wp_reset_query();
                ?>

1 Answer
1

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

<?php
$category = 'whatever';
$new_query = new WP_Query(
    array(
        'post_type'         => 'post',
        'posts_per_page'    => -1,
        'category_name'     => $category;
    )
);

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

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(
    array(
        'taxonomy' => 'people',
        'field'    => 'slug',
        'terms'    => 'bob',
    ),
),

Above example is taken straight from the WordPress Codex.

Leave a Comment