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

I want to create a dynamic direct link to the most recent media (e.g. PDF) based on a category.
I have successfully achieved this with the most recent post using the code below (originally mentioned in this question) but have been unable to translate it to media. Is this possible?

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’ );

Read more here:: How can I link to the most recent media in a media category?

Leave a Reply

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