How can I link to the most recent post in a category?

It’s not built into core, but it’s certainly possible to add, however – I wouldn’t consider it a good idea to have a single post available at multiple URLs, so a redirect is probably best. Of course, it will require a bit of PHP, as WordPress doesn’t operate on magic or willpower.

First, we hook a function to the parse_request action, which runs when WordPress is determining how to set the query vars for the main query.

The following bit of code assumes pretty permalinks are enabled, and category URLs have a category base. Under these conditions, the category_name query var is set, so we can check if this is a request for a category. At the same time, we also check if a latest GET var is set, so together this code will be triggered when a URL looks like:

http://example.com/category/some-category/?latest

If those conditions are met, we query for a single post in the requested category name, via WP_Query, which by default will give us the latest post in that category.

If a post is found, we redirect to that post’s URL via wp_redirect.

This bit of code can go in our theme’s functions.php file:

function wpa_latest_in_category_redirect( $request ){
    if( isset( $_GET['latest'] )
        && isset( $request->query_vars['category_name'] ) ){

        $latest = new WP_Query( array(
            'category_name' => $request->query_vars['category_name'],
            'posts_per_page' => 1
        ) );
        if( $latest->have_posts() ){
            wp_redirect( get_permalink( $latest->post->ID ) );
            exit;
        }

    }
}
add_action( 'parse_request', 'wpa_latest_in_category_redirect' );

Leave a Comment