Hide Buddypress members pages from guests ( also hide BBpress forum posts)

The code below is to hide sections of a WordPress website from guests (hide certain pages or groups of pages on a WordPress , so they are only available for logged in users).

In this case we’re hiding all the Buddypress members pages from guests ( so hiding all pages that start with /members such as member profiles and so on). We’re also  hiding BBpress forum topics ( but they can still view the forums and forum post / topic names ).

If a guest is trying to view a page (that we’re not allowing them to, they are sent to the homepage).

 

add_action( 'template_redirect', 'hf_test_if_user_can_view_this_page', 0 );

function hf_test_if_user_can_view_this_page()
{
    $logged_in = is_user_logged_in();

    if($logged_in !== true){    

        if_guest_trying_to_view_private_page_redirect_them();
    }
}



function if_guest_trying_to_view_private_page_redirect_them(){
    
    $urly = $_SERVER['REQUEST_URI'];    

    $trying_to_view_private = false;
    
    if( startsWith($urly, "/members/") || startsWith($urly, "/forums/topic/") ){        
        $trying_to_view_private = true;         
    }
    
    if($trying_to_view_private === true ){
        redirect_to_homey();
    }
    
}

function startsWith($haystack, $needle)
{
     $length = strlen($needle);
     return (substr($haystack, 0, $length) === $needle);
}

function redirect_to_homey() {
    
    wp_redirect(home_url());
    exit();
  
}

 

Leave a Comment