Setting a 404 in WordPress can be done quite easily using the set_404()
method of WP_Query
and the status_header()
function. Here’s an example taken from WP::handle_404()
:
$wp_query->set_404();
status_header( 404 );
nocache_headers();
If I wanted my tag archive to be accessible to authenticated users only, setting a 404 page for non-authenticated users wouldn’t make sense because the resource does exist, it’s just not available to logged-out users.
My question
How would I set a 401 in WordPress?
1 Answer
The same way you would in any other PHP program:
header("HTTP/1.1 401 Unauthorized");
exit;
WordPress has special handling for 404 because there’s a 404 template. Usually if something happens such as a 401, there is no special template, but you can make use of wp_die
which will show a message in a simple UI
header("HTTP/1.1 401 Unauthorized");
wp_die( 'forbidden' );
This will show the message in a white rectangle with rounded edges and sans-serif text on a gray background, then call exit
/die