Log Every Redirect With Its Source
Writes each redirect WordPress makes to the error log, including the target, status code and the file that triggered it, to track down redirect loops.
Opens WPIDE on
Code
add_filter( 'wp_redirect', function ( $location, $status ) {
$source = '';
foreach ( debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS ) as $frame ) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions
if ( isset( $frame['file'] ) && false === strpos( $frame['file'], 'wp-includes' ) ) {
$source = str_replace( ABSPATH, '', $frame['file'] ) . ':' . ( $frame['line'] ?? '?' );
break;
}
}
$from = isset( $_SERVER['REQUEST_URI'] ) ? esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
error_log( sprintf( '[redirect] %d %s -> %s (from %s)', $status, $from, $location, $source ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
return $location;
}, 999, 2 );
Notes
Meant for troubleshooting; turn it off afterwards as it can write many log lines. Enable WP_DEBUG_LOG to read the entries.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.