wp_redirect
Allows you to change the redirect address passed to the wp_redirect() function.
Usage
add_filter( 'wp_redirect', 'wp_kama_redirect_filter', 10, 2 );
/**
* Function for `wp_redirect` filter-hook.
*
* @param string $location The path or URL to redirect to.
* @param int $status The HTTP response status code to use.
*
* @return string
*/
function wp_kama_redirect_filter( $location, $status ){
// filter...
return $location;
}
- $location(string)
- The path or URL to redirect to.
- $status(integer)
- The redirect status code (HTTP status code).
Examples
#1 Track where a redirect occurs
Sometimes, during debugging, it can be difficult to track (catch, find) which section of code creates redirects in WordPress (it’s hard to catch the redirect). But if such redirects are made by WordPress functions: wp_redirect() or wp_safe_redirect() - there is a solution!
Below is shown how to easily catch redirects.
With debug enabled, use the code (preferably somewhere earlier, e.g. in mu-plugins):
Variant via closure:
add_filter( 'wp_redirect', function( $location ) {
//error_log( print_r( debug_backtrace( 1 ), true ) );
//error_log( print_r( debug_backtrace( 0 ), true ) );
error_log( print_r( debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS ), true ) );
return $location;
} );
Variant via function:
add_filter( 'wp_redirect', 'wp_redirect_print_debug_backtrace' );
function wp_redirect_print_debug_backtrace( $location ) {
error_log( print_r( debug_backtrace( true ), true ) );
// or
/*
ob_start();
debug_print_backtrace();
$log = ob_get_clean();
error_log( $log );
*/
return $location;
}
Check the capabilities of the debug_backtrace function to change the completeness of the data provided.
You can also use the debug_print_backtrace() function, but it immediately outputs the data to the screen, so you need to “buffer” it in order to pass it to error_log().
Now let’s try, for example, visiting the example.com/login/ page, from which the engine will redirect us to the example.com/wp-login.php page. In the log we will get the following information:
Thanks to this debugging information, we determined that the redirect is caused by the following action hook:
add_action( 'template_redirect', 'wp_redirect_admin_locations', 1000 );
It is attached in the default-filters.php file and runs the wp_redirect_admin_locations() function, which creates the redirect itself.
Changelog
| Since 2.1.0 | Introduced. |
Where the hook is called
$location = apply_filters( 'wp_redirect', $location, $status );
Where the hook is used in WordPress
add_filter( 'wp_redirect', array( $this, 'add_state_query_params' ) );