WordPress - Programmatically Getting the Latest Post in a Category

I’ve seen a lot of solutions for this online but I didn’t really like any of them and they didn’t seem to fit my needs. Here is a function I wrote that you can add to your functions.php in your custom theme which will retreive the latest post in a category when you supply the category id:

 * Returns the latest post in a category.
 * Quick explanation:
 * ok, the results from WP_Query are stored in an array of WP_Post objects.
 * the "array keys" in WP_Post are actually just attributes, as in:
 * $latest_post->post_content, etc...
 * @param  [int] $category_id category id by number, use get_cat_ID() with the full category name i.e., get_get_ID('My Example Category') to specify category names.
 * @return [WP_Post] object containing post data
function latest_post_in_category($category_id)
    $latest_posts = get_posts(array(
        'posts_per_page' => 1,
        'category' => $category_id

    $return_post = array();
    if (count($latest_posts) > 0) {
        $latest_post = $latest_posts[0];
        return $latest_post;

    return null;

The function returns null when no post is found. So you can safely check for nulls.

Here is an example of the function in action. I created another function to pull the latest post from a specific category, by its name:

function latest_on_demand()
    return latest_post_in_category(get_cat_ID('On Demand'));

And here’s an example of that function used inside a template:

<?php $latest_post = latest_on_demand() ?>
<?php if (!is_null($latest_post)): ?>
    <?php echo $latest_post->post_content ?>
<?php endif ?>

To get the other attributes of the WP_Post object you can always var_dump($latest_post)

Have fun!

blog comments powered by Disqus