/latest/ Link to Your Newest Post
Makes /latest/ always open your newest post and /latest/category-name/ the newest post in that category, a link that never goes stale for social bios, emails and QR codes.
Opens WPIDE on
Code
// /latest/ opens your newest post; /latest/news/ opens the newest post in the News category.
$wpide_latest_path = 'latest';
add_action( 'template_redirect', function () use ( $wpide_latest_path ) {
// Only when no real page uses the address.
if ( ! is_404() ) {
return;
}
$path = isset( $_SERVER['REQUEST_URI'] ) ? (string) wp_parse_url( wp_unslash( $_SERVER['REQUEST_URI'] ), PHP_URL_PATH ) : '';
$base = untrailingslashit( (string) wp_parse_url( home_url( '/' . trim( $wpide_latest_path, '/' ) ), PHP_URL_PATH ) );
if ( '' === $path || ( strtolower( untrailingslashit( $path ) ) !== strtolower( $base ) && 0 !== stripos( $path, $base . '/' ) ) ) {
return;
}
$category = sanitize_title( trim( substr( $path, strlen( $base ) ), '/' ) );
$cache = get_transient( 'wpide_latest_posts' );
$cache = is_array( $cache ) ? $cache : array();
$post_id = isset( $cache[ $category ] ) ? (int) $cache[ $category ] : null;
if ( null === $post_id ) {
$args = array(
'post_type' => 'post',
'posts_per_page' => 1,
'has_password' => false,
'ignore_sticky_posts' => true,
'no_found_rows' => true,
'fields' => 'ids',
);
if ( '' !== $category ) {
$args['category_name'] = $category;
}
$ids = get_posts( $args );
$post_id = $ids ? (int) $ids[0] : 0;
// Keep at most 50 category answers in the cache.
$cache[ $category ] = $post_id;
set_transient( 'wpide_latest_posts', array_slice( $cache, -50, null, true ), DAY_IN_SECONDS );
}
if ( ! $post_id ) {
return;
}
nocache_headers();
wp_safe_redirect( get_permalink( $post_id ), 302 );
exit;
}, 1 );
// Forget the cached answers whenever a post is published, updated or removed.
add_action( 'transition_post_status', function ( $new_status, $old_status, $post ) {
if ( 'post' === $post->post_type && ( 'publish' === $new_status || 'publish' === $old_status ) ) {
delete_transient( 'wpide_latest_posts' );
}
}, 10, 3 );
Notes
Only used when no real page has that address; change the path at the top of the snippet.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.