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:
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:
And here’s an example of that function used inside a template:
To get the other attributes of the WP_Post object you can always var_dump($latest_post)