Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

For security reasons, to detect if somebody is manipulating GET parameters of the plugin I'm writing, I need to return a 404 if the security query I perform returns nothing. How can I force that? I tried with:

if (security($_GET['id'])) {
    [...]
} else {
    global $wp_query;
    $wp_query->set_404();
}

found it in other posts, but it is not working.

share|improve this question
    
where do you try to do this? or more importantly when? –  Milo Apr 1 at 17:22

1 Answer 1

I have run into the same issue that using $wp_query->set_404(); would properly adjust the global object but not return the 404 template. So in the plugin I was writing I used the tried and tested method:

add_filter( 'template_include', 'wp_139917_force_404' );
function wp_139917_force_404(){
    global $wp_query;
    $wp_query->set_404();
    status_header(404);
    include get_404_template();
    exit;
}

~ modified from source: https://github.com/codearachnid/woocommerce-product-permalink/blob/master/inc/product-permalinks.php#L56

I have alse used this other format which I believe is cleaner and where appropriate should be leveraged:

add_filter( 'template_include', 'wp_139917_sanity_force_404' );
function wp_139917_sanity_force_404( $template ){
    // use your own sanity check logic to return the 404 template
    if( your_sanity_check_true_404() ) {
        global $wp_query;
        $wp_query->set_404();
        return get_404_template();
    } else {
        return $template;
    }
}
share|improve this answer
    
i can't get it to work :( –  Mariano Apr 1 at 21:03
    
do you have a gist/repo where your code is in place? At what point are you attempting to call a 404? –  codearachnid Apr 2 at 11:52
    
the code is only in local at the moment... i back up on a custom error page instead of a 404, don't worry... –  Mariano Apr 2 at 12:23

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.