This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.
Hooks in WordPress can seem a bit daunting at first, but once you get the hang of them, they’re incredibly powerful. One such hook is the redirect_canonical filter. This hook is used to control the behavior of redirects in WordPress. By returning false to this filter, you can cancel the redirect.
To use the redirect_canonical filter, you need to register it using add_filter
. This can be done in the functions.php
file of your active theme or within a custom WordPress plugin. At WePlugins, we recommend creating a custom plugin to ensure your changes are not lost during theme updates.
In the following examples, we’ll define a function weplugins_modify_redirect_canonical_defaults
that takes two parameters. We’ll then register this function with the add_filter
function. The parameters for add_filter
include the hook name (redirect_canonical
), the function name (weplugins_modify_redirect_canonical_defaults
), the priority, and the number of accepted arguments.
Sometimes, you may need to remove a registered hook, which can be done using remove_filter
.
Parameters
- $redirect_url : (string) The redirect URL.
- $requested_url : (string) The requested URL.
Below are the two parameters required for this hook:
Live Example 1: Basic Usage
Below is an example of how you can use this hook to modify the redirect URL:
function weplugins_modify_redirect_canonical_defaults($redirect_url, $requested_url) { // Update the $redirect_url variable according to your website requirements and return this variable. return $redirect_url; } // Add the filter add_filter("redirect_canonical", "weplugins_modify_redirect_canonical_defaults", 10, 2);
Live Example 2: Conditional Redirection
Here’s an example where the redirect URL is modified based on certain conditions:
function weplugins_conditional_redirect($redirect_url, $requested_url) { if (strpos($requested_url, 'special-page') !== false) { $redirect_url = 'https://yourwebsite.com/custom-page'; } return $redirect_url; } // Add the filter add_filter("redirect_canonical", "weplugins_conditional_redirect", 10, 2);
Live Example 3: Removing the Filter
To remove a hook callback, use the example below:
remove_filter("redirect_canonical", "weplugins_modify_redirect_canonical_defaults", 10, 2);
Please make sure to provide the same callback function name, priority, and number of arguments while removing the hook callback.
Contact Us
If you need any customization or assistance with this hook, feel free to contact us.
Explore the latest in WordPress
Trying to stay on top of it all? Get the best tools, resources and inspiration sent to your inbox every Wednesday.