# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Redirects](https://wpide.com/library/category/redirects/)
- Tags: permalinks, migration, 404
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/redirect-old-date-based-urls/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Redirect Old Date-Based Post URLs" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
