Redirecting non-logged in users trying to view Group pages but not the Group directory

We are looking to redirect all Groups pages (but not the Groups directory page /groups/) in BuddyPress for non-logged in users to the /register/ page.

We are currently using this snippet for member profiles in our functions.php file:

/*** Redirect non logged-in users to registration page if they visit a profile page ***/
function gwangi_bp_logged_out_page_template_redirect()
{
    if( ! is_user_logged_in()  bp_is_user() ) {
        wp_redirect( home_url( '/register/' ) );
        exit();
    }
}
add_action( 'template_redirect', 'gwangi_bp_logged_out_page_template_redirect' );

Is there a way this can be modified to also include Group pages (excluding the Groups directory /groups/)? We are unsure and inexperienced on how to go about this.

Any help on this would be appreciated!

Thanks.

Topic wp-redirect buddypress Wordpress

Category Web


It looks like bp_is_group() is "does the current page belong to a single group" (as opposed to bp_is_groups_directory()):

/*** Redirect non logged-in users to registration page if they visit a profile page or a group page other than the groups directory ***/
function gwangi_bp_logged_out_page_template_redirect()
{
    if( ! is_user_logged_in() && ( bp_is_user() || bp_is_group() ) ) {
        wp_redirect( home_url( '/register/' ) );
        exit();
    }
}
add_action( 'template_redirect', 'gwangi_bp_logged_out_page_template_redirect' );

There's more bp_is_* functions in src/bp-core/bp-core-template.php.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.