Implementing global redirection (automatic redirect for all pages who had their slug changed)

Say you have 20 or even 50 pages that needs permalink changes. How can
you guarantee an automatic redirect formation for all of them
afterwards?

The part of a post URL that can be edited in WordPress is called the “slug”. For a URL like http://example.com/blog/abc-xyz, then the “abc-xyz” part would be the slug. The slug is initially formed from the post title, and it can be edited later if desired.

Now, when you change the slug of a post before it is published, then obviously it doesn’t make any difference. When you change the slug of a post which has already been published, then WordPress saves that old slug as “postmeta” data, using a key called “_wp_old_slug”. It does this for any number of old slugs. If you change it three times, then you have three old slugs saved for that post.

When following an old URL, the old slug being used won’t match the current one, because it has been changed. Therefore the main post query will not find the new post. So, WordPress has a function to handle this for old slugs.

During the startup sequence, the wp_old_slug_redirect() function is called by the template_redirect action. If the normal query was successful, then the function returns and does nothing at all. However, if the query was unsuccessful, and a slug was provided in the URL, then this function performs a search of the postmeta looking for a match amongst those old slug values. If it finds a match, then it gets the newer correct URL (permalink) for that post, and sends back a 301 redirect for it.

So, short answer to your question: WordPress handles this case automatically. Built right in.

For reference, this functionality was added to WordPress in version 2.1.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)