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.

There are some pages on my BuddyPress install that I would like to hide by printing a 404 error.

With the help of the following question: Redirect Restricted Page to 404 I came up with this code:

global $wp_query;
$wp_query->set_404();
status_header( 404 );
get_template_part( 404 );
exit();

Most of the page is hidden nicely and a 404 error is printed, however what has been printed before this code remains (including the header title of the page I want hidden).

Unfortunately I can't move this code higher up, before anything gets printed.

So is there a way to clear everything that has been printed before and then print a fresh 404 error but with keeping the current URL? (So no redirection to the 404.php page.)

share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

You should be using a filter outside of your template for this:

add_filter( 'template_include', 'wpa62226_template_include', 1, 1 );
function wpa62226_template_include( $template ){
    if( is_page( 'some-page' ) ) :
        global $wp_query;
        $wp_query->set_404();
        status_header( 404 );
        $template = locate_template( '404.php' );
    endif;
    return $template;
}

Your code is executed before the template is loaded, so it becomes a non-issue.

share|improve this answer
    
I tried to add this filter to the functions.php and to the bp-custom.php files but neither seem to work. Are you sure this is supposed to work on BuddyPress? –  Paul T. Aug 20 '12 at 1:57
    
It seems that the code is never run at all. I tried the following code to test for that: add_filter( 'template_include', 'hide_page_template_include', 1, 1 ); function hide_page_template_include( $template ) { return locate_template( '404.php' ); } Nothing happens at all, so it seems that this does not work on BuddyPress. (The expected behavior was for it to print a 404 error page for any page that is called.) –  Paul T. Aug 20 '12 at 1:58
1  
I'm not familiar with BuddyPress, but it's possibly an issue of priority. You can inspect the global $wp_filter to see if BP is adding its own filter, or try altering priority. –  Milo Aug 20 '12 at 3:27
    
Tried it in the functions.php page instead of bp-custom.php with the wp filter and it works like a charm! Thanks! :) –  Paul T. Sep 3 '12 at 17:50
add comment

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.