Change permalink only on new posts

Your permalink structure is global; it is not a property of individual posts. There is no way to indicate that one post uses a certain permalink structure while another uses a different one.

This makes sense when you think about how WordPress processes requests. Using the new structure, WordPress maps the request to index.php?name=$1 where $1 is the post slug portion of the request. WordPress then queries the database for a post with a slug that matches the request.

If every post had its own permalink structure, WordPress would have to iterate over every single post until it found one with a permalink structure that matched the request.

What you can do is redirect your old permalinks to the new permalinks. There are a couple of ways you can go about doing this:


.htaccess

You can add the following to your .htaccess file, before the WordPress rewrite rules:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^[0-9]{4}/[0-9]{2}/(.*)$ /$1 [R=301,L]
</IfModule>

This will match the year/month/postname structure and redirect to the postname structure.

add_rewrite_rule

You can use add_rewrite_rule to create an additional rule that matches your old permalink structure.

add_action('init', function() {
    flush_rewrite_rules();
    add_rewrite_rule('^([0-9]{4})/([0-9]{2})/(.*)$', 'index.php?name=$matches[3]', 'bottom');
});

This accomplishes the same thing as the .htaccess method. If you use this approach make sure you flush your rewrite rules by visiting the Settings > Permalinks page in your backend.


Regardless of which approach you use, the canonical URL for your posts will use the new permalink structure. Requests using the old permalink structure will be redirected to the new structure.

Search engines will eventually catch on to the change and index the new structure rather than the old structure. At that point, you can drop the additional rewrite rules, so long as you don’t have any internal links using the old structure.

If you do have internal links using the old structure, I would use this utility to do a regex search and replace. Just make sure you make a backup of your database.

If you are concerned about inbound links using the old structure, there isn’t much you can do other than keep the rewrite rules indefinitely.

Leave a Comment