Last active
May 6, 2020 01:20
-
-
Save tannerhodges/2e28476d1c3ea1064c1ad88c42d2b8e7 to your computer and use it in GitHub Desktop.
WordPress `throw_404()` helper.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Throw a 404 error and render the current theme's 404 template. | |
* | |
* @see https://richjenks.com/wordpress-throw-404/ | |
* @see https://developer.wordpress.org/reference/hooks/pre_get_document_title/ | |
*/ | |
function throw_404() { | |
// 1. Ensure `is_*` functions work. | |
global $wp_query; | |
$wp_query->set_404(); | |
// 2. Reset HTML title. | |
// NOTE: 👇 Change this to customize your site's 404 title. | |
add_filter( 'pre_get_document_title', function () { | |
return 'Page Not Found'; | |
}, 999 ); | |
// 3. Return a 404 status code. | |
status_header( 404 ); | |
nocache_headers(); | |
// 4. Show 404 template. | |
require get_404_template(); | |
// 5. Stop execution. | |
exit; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment