Skip to content

Instantly share code, notes, and snippets.

@tannerhodges
Last active May 6, 2020 01:20
Show Gist options
  • Save tannerhodges/2e28476d1c3ea1064c1ad88c42d2b8e7 to your computer and use it in GitHub Desktop.
Save tannerhodges/2e28476d1c3ea1064c1ad88c42d2b8e7 to your computer and use it in GitHub Desktop.
WordPress `throw_404()` helper.
<?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