Is there a best-practices example of middleware for Wordpress?

I’m not sure if I am approaching this problem the right way. I am building a web portal for one of our clients that will have 6 different user roles. Each role may or may not have access to a route, depending on if their role(s) require access to each route.

This is a current implementation for my guest routes:

// REDIRECT GUESTS TO GUEST ROUTES
function guest_redirect() {
    $guest_routes = array(
        'member-login', 
        'member-account', 
        'member-register', 
        'member-password-lost', 
        'member-password-reset'
    );
    // FORCE USER LOGIN OR REGISTRATION
    if ( !is_user_logged_in() && !is_page($guest_routes) ) {
      wp_redirect( 'member-login' ); 
      exit;
    }
}
add_action( 'template_redirect', 'guest_redirect' );

Security is also a priority. All users (members) may interact with client staff and administrators, but no members may ever see any other member within the app. There are particular exceptions to this, if two members decide to have a “spouse” relationship then they are able to share and interact as they do with staff & admins.

So I’m not sure if I’m missing a key area of Wordpress that solves this issue or if what I’m doing is the correct way to go. Any advice or direction would be greatly appreciated.

Thanks for your help,

Luke

1 Like

There are a handful of groups/user access plugins for WordPress that may accomplish what you’re looking for:

I’d check those out - most of them are extensible, if they don’t provide what you need out of the box.

I suggest you to do the logic directly in your composer and render the view in base on it

Like this handler in app/view/composer!
public function handle($request, $next) {
// Middleware logic goes here
// Example: Check if the user is logged in
if (!is_user_logged_in()) {
// Redirect to a specific page or perform some action
wp_redirect(home_url(‘/login’));
exit;
}
}