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).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | 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(); } |
Disclaimer: All content on this site, is use at your own risk (Always backup before changing anything in your software/database/servers etc). Techs change, go out of date etc...
I/we accept no liability if anything you use on this site adversely affects you.