Skip to content

Code Snippet: Display latest Post per WordPress Category

Blog  ✺  WordPress  ✺  Code Snippet

A while ago a client wanted to display the latest post per category on the WordPress blog page. The goal was to respect sticky posts and therefore exclude the category used by the latest sticky post. WordPress offers the pre_get_posts action hook to alter the WP_Query instance before it runs the query on the database.

Check out the Gist with the code snippet and alter it according to your use case. Add the code to your functions.php file, make sure to use a child theme to ensure the code doesn’t get overwritten by theme updates.

Let me know how you used pre_get_posts to alter queries in your WordPress projects.


You might like

WordPress Mega Menu with Blocks


Building a custom driver for Favicon Fetcher