Hiding bbPress topics from logged out users

I just spent hours figuring this out so I thought I’d try and save others the bother by sharing it here.

The basic aim was to hide the contents of topics in a bbPress 2.0 forum from any users not logged in. This makes for a nice private forum.

I found suggestions about making forums hidden, private and so on but none of them really worked as they hid them for logged in users too.

My final solution was to make bbPress ‘dumb’ when it comes to logged out users. I.e., it could either be clever and say “there are topics, but you’re not allowed to see them until you login” or it could just say “there are no topics”.

The following code does the latter, dumb version by hooking into the forums, topics and replies loops.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function pj_hla_logged_in_topics($have_posts){
    if (!is_user_logged_in()){
        $have_posts = null;
    }
    return $have_posts;
}
add_filter('bbp_has_topics', 'pj_hla_logged_in_topics');
add_filter('bbp_has_forums', 'pj_hla_logged_in_topics');
add_filter('bbp_has_replies', 'pj_hla_logged_in_topics');

I simply placed this within my theme’s functions.php but you could just as easily wrap this in a plugin.

3 comments

  1. Hi John!

    Awesome workaround!

    We’ve taken it a little further and added a warning dialogue box to let users know that they have to log-in to see the forums. Otherwise the default message may be slightly misleading.

    (Hope this formats well in comments)

    Cheers!
    Spence

    /*———————————————————————————–*/
    /* Hide bbPress topics from viewers not logged-in */
    /*———————————————————————————–*/

    function lab_logged_in_bbptopics($have_posts){
    if (!is_user_logged_in()){
    $log_in = ‘Sorry, you must be logged-in to view the forums!’;
    $have_posts = null;

    }
    echo $log_in;
    return $have_posts;
    }
    add_filter(‘bbp_has_topics’, ‘lab_logged_in_bbptopics’);
    add_filter(‘bbp_has_forums’, ‘lab_logged_in_bbptopics’);
    add_filter(‘bbp_has_replies’, ‘lab_logged_in_bbptopics’);

Leave a Reply

Stop SOPA