The redirect_canonical() WordPress PHP function redirects incoming links to the proper URL based on the site URL, improving SEO by avoiding duplicate content penalties.
Usage
To use the redirect_canonical() function, you can create a custom function that checks for specific conditions and then hooks it to the ‘template_redirect’ action.
function custom_redirect_canonical() { // Your conditions and logic here } add_action('template_redirect', 'custom_redirect_canonical');
Parameters
- $requested_url (string) – Optional. The URL that was requested, used to figure if redirect is needed. Default: null
- $do_redirect (bool) – Optional. Redirect to the new URL. Default: true
More information
See WordPress Developer Resources: redirect_canonical
Examples
Create 301 redirects for canonical URLs
This example creates 301 redirects for single posts to ensure the correct URL is used:
function wpdocs_redirect_can() { if (is_single()) { global $wp; $wp->parse_request(); $current_url = trim(home_url($wp->request), '/'); $redirect = get_permalink(); $surl = trim($redirect, '/'); if ($current_url !== $surl) { wp_redirect($redirect, 301); exit; } } } add_action('template_redirect', 'wpdocs_redirect_can');
Remove redirect for custom taxonomy with a specific query variable
This example removes the canonical redirect for a custom taxonomy ‘event_category’ when the ‘year’ query variable is present:
add_filter('redirect_canonical', 'pick_event_year_redirect', 10); function pick_event_year_redirect($redirect_url) { if (is_tax('event_category') && is_year()) { return ''; } return $redirect_url; }
Redirect non-www to www
This example redirects non-www URLs to www URLs for better SEO:
function force_www_redirect() { if (strpos($_SERVER['HTTP_HOST'], 'www.') === false) { wp_redirect('https://www.' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], 301); exit; } } add_action('template_redirect', 'force_www_redirect');
Redirect posts to a custom URL
This example redirects all posts to a custom URL based on the post ID:
function redirect_posts_to_custom_url() { if (is_single()) { $post_id = get_the_ID(); $new_url = home_url('/custom-url/') . $post_id; wp_redirect($new_url, 301); exit; } } add_action('template_redirect', 'redirect_posts_to_custom_url');
Redirect a specific page to another URL
This example redirects a specific page with the slug ‘old-page’ to another URL:
function redirect_old_page_to_new_url() { if (is_page('old-page')) { $new_url = 'https://example.com/new-page/'; wp_redirect($new_url, 301); exit; } } add_action('template_redirect', 'redirect_old_page_to_new_url');