Redirect WordPress Page to Latest Post
March 08, 2024A WordPress code snippet to redirect a page to the most recent post.
For my Twitch streams I would share a “Today On Stream” page that would have a running log of what I’d been working on that day, useful for those popping in wanting to know what I was working on. This log would eventually be copied over to a new post and turned into a stream summary at the end that I would share for my own record and those who missed out.
This copy-pasta was tedious and I wanted to automate a way where the page would instead redirect to the latest post of a custom post type that I could edit during stream and polish up at the end.
So here’s a little code snipppet to add to the functions.php file that can be modified:
Code
If the page matches the page name in the function, it will return the most recent post of the given post type if it exists and redirect the page to that post.
add_action('template_redirect', 'FUNCTION_NAME');
function FUNCTION_NAME()
{
if ( is_page('PAGE_NAME'))
{
$posts = get_posts( array(
'post_type' => 'POST_TYPE',
'posts_per_page' => 1,
'orderby' => array('post_date' => 'DESC')
));
if (!empty ($posts))
{
wp_redirect(get_permalink($posts[0]), 302);
exit();
}
}
}
Replace FUNCTION_NAME with what you want this function to be called.
Replace PAGE_NAME with the name of the page.
Replace POST_TYPE with the type of post to get, if it is a post this would be ‘post’ but if you are using a custom post type, this would be the name of the cpt.
Wordpress References
Hook: template_redirect
Function: is_page
Function: get_posts
Function: wp_redirect