| 1 |
<?php |
| 2 |
|
| 3 |
/** |
| 4 |
* Return an error to the client, and trigger the WordPress error page |
| 5 |
*/ |
| 6 |
class Error_Action extends Red_Action { |
| 7 |
/** |
| 8 |
* Set WordPress to show the error page |
| 9 |
* |
| 10 |
* @return void |
| 11 |
*/ |
| 12 |
public function run() { |
| 13 |
wp_reset_query(); |
| 14 |
|
| 15 |
// Set the query to be a 404 |
| 16 |
set_query_var( 'is_404', true ); |
| 17 |
|
| 18 |
// Return the 404 page |
| 19 |
add_filter( 'template_include', [ $this, 'template_include' ] ); |
| 20 |
|
| 21 |
// Clear any posts if this is actually a valid URL |
| 22 |
add_filter( 'pre_handle_404', [ $this, 'pre_handle_404' ] ); |
| 23 |
|
| 24 |
// Ensure the appropriate http code is returned |
| 25 |
add_action( 'wp', [ $this, 'wp' ] ); |
| 26 |
} |
| 27 |
|
| 28 |
/** |
| 29 |
* Output selected HTTP code, as well as redirection header |
| 30 |
* |
| 31 |
* @return void |
| 32 |
*/ |
| 33 |
public function wp() { |
| 34 |
status_header( $this->code ); |
| 35 |
nocache_headers(); |
| 36 |
|
| 37 |
global $wp_version; |
| 38 |
|
| 39 |
if ( version_compare( $wp_version, '5.1', '<' ) ) { |
| 40 |
header( 'X-Redirect-Agent: redirection' ); |
| 41 |
} else { |
| 42 |
header( 'X-Redirect-By: redirection' ); |
| 43 |
} |
| 44 |
} |
| 45 |
|
| 46 |
public function pre_handle_404() { |
| 47 |
global $wp_query; |
| 48 |
|
| 49 |
// Page comments plugin interferes with this |
| 50 |
$wp_query->posts = []; |
| 51 |
return false; |
| 52 |
} |
| 53 |
|
| 54 |
public function template_include() { |
| 55 |
$template = get_404_template(); |
| 56 |
|
| 57 |
if ( ! is_string( $template ) || $template === '' ) { |
| 58 |
$template = get_index_template(); |
| 59 |
} |
| 60 |
|
| 61 |
return $template; |
| 62 |
} |
| 63 |
|
| 64 |
public function name() { |
| 65 |
return __( 'Error (404)', 'redirection' ); |
| 66 |
} |
| 67 |
} |
| 68 |
|