wp_old_slug_redirect()
The core function that redirects the user from old post links to the current one.
The function works only with flat (non-hierarchical) post types.
The function is triggered on the hook template_redirect:
add_action( 'template_redirect', 'wp_old_slug_redirect' );
This function should not be used anywhere, it is used in the core automatically.
To show how the function works, let's consider an example:
Suppose we had a post with the title "Привет" and the link example.com/привет. We changed the slug of the post and the link became example.com/privet. During the slug change, WP automatically saved the old slug in the meta-field _wp_old_slug - it recorded %d0%bf%d1%80%d0%b8%d0%b2%d0%b5%d1%82 — the word "привет" processed by urlencode().
Now, if you go to the old address example.com/привет, before showing the user a 404 error, WP calls wp_old_slug_redirect(), which uses the functions _find_post_by_old_slug() or _find_post_by_old_date() to try to find the ID of the post that previously had the requested slug or date in the URL (searching the meta-field _wp_old_slug or _wp_old_date). If the post is found, the function redirects to the new address with a 301 server response.
Searching by date is needed when the permalink uses a date. In this case, when the post date is changed, the old date is saved in the meta-field _wp_old_date.
A post can have as many old slugs as needed.
Hooks from the function
Returns
null. Nothing (null).
Usage
wp_old_slug_redirect();
Examples
#1 Disable redirection from old slugs (post_names)
By default, when visiting each individual non-hierarchical post, WP makes a query to the database and checks all _wp_old_slug meta-fields of all posts to see if there is a shortcut from the current query. If such a meta-field is found, the current request is considered as the old URL of the post, so a redirect to the new URL of the posts is made.
If you don't need this behavior (not recommended), you can disable such redirections (checks) like so:
remove_action( 'template_redirect', 'wp_old_slug_redirect' );
For the query, see function _find_post_by_old_slug().
Changelog
| Since 2.1.0 | Introduced. |