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;
status_header( 404 );
get_template_part( 404 );

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.)

1 Answer 1


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;
        status_header( 404 );
        $template = locate_template( '404.php' );
    return $template;

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

  • 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, 2012 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, 2012 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, 2012 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, 2012 at 17:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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