Redirect Old Date-Based Post URLs
After switching from /2019/05/post-name/ style permalinks to plain post names, sends visitors and search engines from the old dated addresses to the right posts.
Opens WPIDE on
Code
add_action( 'template_redirect', function () {
if ( ! is_404() ) {
return;
}
$path = isset( $_SERVER['REQUEST_URI'] ) ? (string) wp_parse_url( wp_unslash( $_SERVER['REQUEST_URI'] ), PHP_URL_PATH ) : '';
if ( ! preg_match( '#/\d{4}/\d{1,2}/(?:\d{1,2}/)?([^/]+)/?$#', $path, $match ) ) {
return;
}
$post = get_page_by_path( sanitize_title( rawurldecode( $match[1] ) ), OBJECT, 'post' );
if ( ! $post || 'publish' !== $post->post_status ) {
return;
}
$target = get_permalink( $post );
if ( untrailingslashit( (string) wp_parse_url( $target, PHP_URL_PATH ) ) !== untrailingslashit( $path ) ) {
wp_safe_redirect( $target, 301 );
exit;
}
} );
Notes
Only runs when the old address would otherwise be a 404.
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.