WordPress: custom function to redirect posts if a specific meta field is empty
In this example, I have a custom post type called "partner". When the meta field "header_2" is empty, the post single should not be active, which is why I want it to post to 404. I wrote a custom function that redirects to 404 if the field is empty.
add_action( 'template_redirect', 'redirct_if_empty' );
function redirct_if_empty() {
if (!is_singular( 'partner') ) {return false;}
global $post;
$field = get_post_meta( $post->ID, 'header_2', true );
if ( empty( $field ) ) {
header("HTTP/1.1 404 Not Found");
header("Location:" . get_template_part( 404 )); /* Redirect browser */
exit();
}
}
How do I check my website's status code?
You can use DevTools in Google Chrome (F12 + "Network" tab) and the first element should be your website's status code at type "document"