I’d like to set up my WP so that urls ending in /last would return the most recent post in that set of posts. For example, /last returns the most recent post of any type, archives/category/trivia/last would return the most recent post categorized as trivia, and archives/LoomSong/last would return the most recent custom post of type=”LoomSong”.

I think I need to add rewrite rules, but I’m very unsure of what the regex should be. So far this is what I have:

add_action( 'init', 'ASHmostrecent_init' );
function ASHmostrecent_init(){
    add_rewrite_rule( 'last/?$', 'WHAT DO I PUT HERE?');
}

add_filter( 'query_vars', 'ASHmostrecent_query_vars' );
function ASHmostrecent_query_vars( $query_vars ){
    $query_vars[] = 'ASHmostrecent_filter';
    return $query_vars;
}

3 Answers
3

add_action( 'init', 'ASHmostrecent_init' );
function ASHmostrecent_init(){
    add_rewrite_rule( 'last/?$', 'index.php?post_type=post&posts_per_page=1');
}

A query already pulls up posts starting from the latest to the oldest, so all you have to do is limit what’s returned by one. posts_per_page does this; limiting by one will give you the latest post. Edit the post_type accordingly.

Leave a Reply

Your email address will not be published. Required fields are marked *