3

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

2

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.

4
  • So with this function, I can filter by category? Reading documentation, looks like $query = new WP_Query( array( 'category_name' => 'staff' ) );?
    – WashDCDev
    Commented Dec 14, 2016 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. Commented Dec 15, 2016 at 7:40
  • @WashDCDev I have amended my answer with both the category and tax_query code. Commented Dec 15, 2016 at 10:52
  • Cool; excellent answer.
    – WashDCDev
    Commented Dec 15, 2016 at 14:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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