does anyone tried creating a login form specifically for Subscribers? meaning if the user roles are admins, contributors, authors are not able to login on that said form only subscriber users. Thanks!
does anyone tried creating a login form specifically for Subscribers? meaning if the user roles are admins, contributors, authors are not able to login on that said form only subscriber users. Thanks!
Here is a snipped. Make sure to run this code after the users are logged in
//To get logged in user information
$user = wp_get_current_user();
//Condition to check weather user is subscriber or not
if ( in_array( 'subscriber', (array) $user->roles ) ) {
//The user has the "subscriber" role
}else{
// redirect user to different section and end their session
wp_logout(); // user is logged out
wp_redirect( home_url( '/' ) ); // user is redirected to home page
}
Do let me know if this works for you or not
You can create a custom login form that restricts access to subscribers only by checking the user role during the login process.
Create a new page template for your custom login page
Add the following code to custom-login.php
<?php
/**
* Template Name: Custom Login
*/
// Check if user is already logged in, if yes, redirect to home page
if (is_user_logged_in()) {
wp_redirect(home_url());
exit;
}
// Check if form is submitted
if (isset($_POST['submit'])) {
$username = sanitize_text_field($_POST['username']);
$password = $_POST['password'];
// Attempt login
$user = wp_signon(array(
'user_login' => $username,
'user_password' => $password,
'remember' => true,
));
// Check if login successful
if (is_wp_error($user)) {
$error_message = $user->get_error_message();
} else {
// Redirect user after successful login
wp_redirect(home_url());
exit;
}
}
?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo('charset'); ?>">
<title><?php bloginfo('name'); ?> - Custom Login</title>
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<div id="login-form">
<h2>Login</h2>
<?php if (isset($error_message)) : ?>
<p class="error"><?php echo $error_message; ?></p>
<?php endif; ?>
<form method="post" action="">
<p>
<label for="username">Username</label>
<input type="text" name="username" id="username" required>
</p>
<p>
<label for="password">Password</label>
<input type="password" name="password" id="password" required>
</p>
<p>
<input type="submit" name="submit" value="Login">
</p>
</form>
</div>
<?php wp_footer(); ?>
</body>
</html>
After that create a new page in Wordpress admin and assign the template Custom Login to it.