The ‘redirect_canonical’ WordPress PHP filter allows you to modify the canonical redirect URL.
By returning false to this filter, you can cancel the redirect altogether.
Usage
add_filter( 'redirect_canonical', 'my_function_name', 10, 2 ); function my_function_name( $redirect_url, $requested_url ) { // Your code here return $redirect_url; }
Parameters
- $redirect_url (string): The URL the user will be redirected to.
- $requested_url (string): The URL the user requested.
Examples
Prevent Canonical Redirect on a Custom Post Type
add_filter( 'redirect_canonical', 'prevent_redirect_on_custom_post_type', 10, 2 ); function prevent_redirect_on_custom_post_type( $redirect_url, $requested_url ) { if ( is_singular( 'custom_post_type' ) ) { return false; } return $redirect_url; }
This code snippet prevents canonical redirect on a custom post type called “custom_post_type”. If the requested URL is of that custom post type, the redirect is cancelled.
Stop Redirect for a Specific Page
add_filter( 'redirect_canonical', 'stop_redirect_for_specific_page', 10, 2 ); function stop_redirect_for_specific_page( $redirect_url, $requested_url ) { if ( is_page( 'no-redirect-page' ) ) { return false; } return $redirect_url; }
In this example, the canonical redirect is stopped for a specific page with the slug “no-redirect-page”.
Disable Canonical Redirect for Attachment Pages
add_filter( 'redirect_canonical', 'disable_redirect_for_attachment_pages', 10, 2 ); function disable_redirect_for_attachment_pages( $redirect_url, $requested_url ) { if ( is_attachment() ) { return false; } return $redirect_url; }
This code disables the canonical redirect for all attachment pages on the website.
Prevent Redirect for a Certain Category
add_filter( 'redirect_canonical', 'prevent_redirect_for_category', 10, 2 ); function prevent_redirect_for_category( $redirect_url, $requested_url ) { if ( is_category( 'no-redirect-category' ) ) { return false; } return $redirect_url; }
Here, the canonical redirect is prevented for a category with the slug “no-redirect-category”.
Redirect Logged-In Users to Dashboard
add_filter( 'redirect_canonical', 'redirect_logged_in_users', 10, 2 ); function redirect_logged_in_users( $redirect_url, $requested_url ) { if ( is_user_logged_in() && is_front_page() ) { return admin_url(); } return $redirect_url; }
This example checks if the user is logged in and on the front page. If so, the user is redirected to the dashboard.