Wordpress re-direct if specific user is already logged in - php

I currently have two members areas set up within a site. If a user logs in, and then decides to browse around the general website, when they click on the 'Members Area' icon again I want that page to work out which user is logged in, and then re-direct them to the correct members area. If no user is logged in, it should display the log in form.
I currently have the following:
<?php
if ( $session->logged_in ) {
if ( $username == "user1" ) {
wp_redirect ( home_url("/members-area-1") );
exit; }
} elseif ( $username == "user2" ) {
wp_redirect ( home_url("/members-area-2") );
exit;
} else {
?>
Currently it doesnt re-direct, it just displays the login form regardless of which user I'm logged in as. Any suggestions on how to make this work correctly?
(Be gentle, I'm still fairly raw when it comes to wordpress and php dev)
Many thanks,

You may try this
if ( is_user_logged_in() )
{
global $current_user;
if( $current_user->user_login == 'user1' )
{
wp_redirect( home_url("/members-area-1") );
}
elseif( $current_user->user_login == 'user2' )
{
wp_redirect( home_url("/members-area-2") );
}
else
{
// logged in but doesn't match
}
}
See is user logged in() at codex.
Update: To solve the header sent warning issue you can add following code in your functions.php file to enable output buffering
add_action('init', 'buffer_start');
add_action('wp_footer', 'buffer_end');
function callback($buffer) { return $buffer; } // This is not necessury if you don't use callback argument in the ob_start function.
function buffer_start() { ob_start("callback"); }
function buffer_end() { ob_end_flush(); }

Related

How to redirect a button to a different page based on used login on Wordpress

I have a button that I have that leads users to a page on WordPress called /portfolio/, so is there a way that I can redirect users to the /registration/ page until their logged in?
I'm using a plugin on WordPress that uses the below code to change the menu per user logged in/logged out.
function my_wp_nav_menu_args( $args = '' ) {
if( is_user_logged_in() ) {
$args['menu'] = 'logged-in';
} else {
$args['menu'] = 'logged-out';
}
return $args;
}
add_filter( 'wp_nav_menu_args', 'my_wp_nav_menu_args' );
Is there a way that I can use the if( is_user_logged_in() ) to do the same with a redirect? I can't seem to lock the page down to all users.
You could so something like this?
if(!is_user_logged_in()) {
//If user not logged in
echo "<script> location.href='http://somesite/registration/'; </script>";
}
This should work if you arent using jquery as its JavaScript.

Allow only the login and password reset page for guest on WordPress

I'm currently using the following solution in my functions.php file to force visitors that aren't logged in to do so:
// force visitors to log in to see the page
function admin_redirect() {
if ( !is_user_logged_in()) {
wp_redirect( home_url('wp-admin') );
exit;
}
}
add_action('get_header', 'admin_redirect');
But now I'm facing the problem that no-one can reset their password, because they are redirected to /wp-admin/.
How can I exclude the URL /my-account/lost-password/ ?
Thank you in advance!
replace pageid with page id or slug of forget password page
if ( (!is_user_logged_in()) && (!is_page(pageid))) {
wp_redirect( home_url('wp-admin') );
exit;
}
}
add_action('get_header', 'admin_redirect');
This solved my problem.
My final solution:
function admin_redirect() {
if ( (!is_user_logged_in()) && (!is_page("my-account"))) {
wp_redirect( home_url('wp-admin') );
exit;
}
}
add_action('get_header', 'admin_redirect');

Only allow specific user roles to log into WordPress site

I currently have a WP site setup with a unique 'multisite' plugin installed specifically to allow for a single admin area of WooCommerce products, but with 2 different front-ends based on 2 different domains, with separate themes.
One of the sites is a 'wholesale' site while the other is 'retail'. The wholesale site should only allow trade customers to make purchases. The problem lies in that both sites are sharing a single domain, and therefore user accounts.
The problem: I need to ensure if a user who is does not have the user role 'trade_customer' tries to log into the wholesale site, the role is checked and the user is logged out, redirected to login page with a notification. So far I have the following in functions.php:
function trade_customers_only() {
function get_user_role() {
global $current_user;
$user_roles = $current_user->roles;
$user_role = array_shift($user_roles);
return $user_role;
}
$the_current_role = get_user_role();
echo $the_current_role;
if( $the_current_role != 'administrator' ) {
$logout_url = wp_login_url().'?mode=tradeonly';
wp_destroy_current_session();
wp_logout();
wp_redirect( $logout_url, 302 );
exit();
}
}
add_action('wp_login', 'trade_customers_only');
// CUSTOM LOGIN MESSAGES
function my_login_message() {
if( $_GET['mode'] == 'tradeonly' ){
$message = '<p class="message"><b>You must be a Trade Customer to access this site.</b></p>';
return $message;
}
}
add_filter('login_message', 'my_login_message');
This code is currently: returning the logged in user to wp-login.php and adding the note "You must be a trade customer... etc". However, after the first login attempt with any user role, every other login attempt does the same redirect and shows message. Is my code incorrect or is there some WP session cookie in the DB or browser causing the problem whereby WP thinks I am not using an admin account?
The first time I attempted login was with admin account. it worked and went to dashboard. Next attempt was with a customer role account. The redirect and note occurred. A following attempt with admin account only did the redirect with note, but no dashboard access.
1) Change your trade_customers_only function:
function trade_customers_only($login, $user) {
if( $user->roles && !in_array('administrator',$user->roles)) {
$logout_url = wp_login_url().'?mode=tradeonly';
wp_destroy_current_session();
wp_logout();
wp_redirect( $logout_url, 302 );
exit();
}
}
And fix your action call:
add_action('wp_login', 'trade_customers_only',10,2);
2) The other solution is using authenticate filter instead of using wp_login action. The difference is that you check for the user's role before user's session sets, so you don't need to destroy it.
add_filter('authenticate',function($user,$username) {
if (!is_wp_error($user)) {
$auth_user=get_user_by('login',$username);
if ($auth_user && !in_array('administrator',$auth_user->roles)) {
return new WP_Error('authentication_failed', '<p class="message"><b>You must be a Trade Customer to access Key Essentials. Are you looking for Love Tillys?</b></p>');
}
}
return $user;
},100,2);
My new full code is now:
function trade_customers_only($login, $user) {
if( $user->roles && !in_array('administrator',$user->roles)) {
$logout_url = wp_login_url().'?mode=tradeonly';
wp_destroy_current_session();
wp_logout();
wp_redirect( $logout_url, 302 );
exit();
}
}
add_action('wp_login', 'trade_customers_only',10,2);
// CUSTOM LOGIN MESSAGES
function my_login_message() {
if( $_GET['mode'] == 'tradeonly' ){
$message = '<p class="message"><b>You must be a Trade Customer to access this site.</b></p>';
return $message;
}
}
add_filter('login_message', 'my_login_message');
This code works properly. However as Kulivov Sergey mentioned in his reply, using the authenticate filter instead of the wp_login action is better for what I need to achieve. Using:
add_filter('authenticate',function($user,$username) {
if (!is_wp_error($user)) {
$auth_user=get_user_by('login',$username);
if ($auth_user && !in_array('administrator',$auth_user->roles)) {
return new WP_Error('authentication_failed', '<p class="message"><b>You must be a Trade Customer to access this site.</b></p>');
}
}
return $user;
},100,2);
Not only checks for the user role without logging in and creating a session, it also keeps the user on their current page with no redirection, which is great.
I have tested the below code as working correctly.
There's no need to run wp_destroy_current_session() or wp_logout(), just simply return an error instead and it will interrupt authentication and show your error message on the login page.
You might have to make sure the priority is last (100 in this case), so that existing filters wp_authenticate_username_password, wp_authenticate_email_password and wp_authenticate_spam_check all do their thing and before the user is fully logged in that you will then deny.
/* Only allow administrators to login */
add_filter( 'authenticate', 'my_admin_check', 100, 1 );
function my_admin_check( $user ) {
// Make sure this is a real login attempt, without errors
if ( !is_wp_error($user) ) {
$user_role = $user->roles[0];
// add or remove the roles you want to allow/disallow (can be a custom role or regular WordPress roles)
if ( !in_array( $user_role, array( 'trade_customer' ) ) ){
return new WP_Error( 'login_failed', __( "Only staff can use this login.", "mysite_domain" ) );
} else {
// allow the login
return $user;
}
} else {
// We're just loading the login page, not running a login.
return $user;
}
}

How to deactivate redirect for non-logged in users on specific pages?

I created a website wide (wordpress) redirect for non-logged in users by adding the following code to my function.php file:
function admin_redirect() {
if ( !is_user_logged_in()) {
wp_redirect( home_url('/login') );
exit;
}
}
add_action('get_header', 'admin_redirect');
However there are a few pages, which should be accessible for non-logged in users. Any ideas how to solve the problem?
Thanks for your help!
Check conditionally tags in your funciton
https://codex.wordpress.org/Conditional_Tags
function admin_redirect() {
if( is_page('about_us') )
return;
if ( !is_user_logged_in()) {
wp_redirect( home_url('/login') );
exit;
}
}

redirection of login form in wordpress

I'm using wp_login_form() on a site at the moment, and when you log in correctly it redirects the user to the appropriate URL.
Unfortunately if you make a mistake in the username/password it forwards you to wp-login.php, which shakes its box at the user. And disrupts consistent brand experience, like.
So does anybody know a way to make it not do that?
Try this :
This will let you include the header and footer of the theme at login page
add_action( 'login_head', 'wp_custom_login_header' );
function wp_custom_login_header() {
wp_enqueue_style( 'wp-custom-login' );
do_action('wp_custom_login_header_before');
get_header();
do_action('wp_custom_login_header_after');
}
add_action( 'login_footer', 'wp_custom_login_footer' );
function wp_custom_login_footer() {
do_action('wp_custom_login_footer_before');
get_footer();
do_action('wp_custom_login_footer_after');
}
function wp_custom_login_is_login_page() {
return in_array($GLOBALS['pagenow'], array('wp-login.php', 'wp-register.php'));
}
By saying you use the wp_login_form() function, I'm guessing you use a custom form on its own page.
There are a couple of things you can do.
If this form is on it's own page and you just want the incorrect password/username to go back to that page and alert the user, you can create a function in your functions.php file which will do a redirect to the referring page like so:
add_action( 'wp_login_failed', 'my_front_end_login_fail' ); // hook failed login
function my_front_end_login_fail( $username ) {
$referrer = $_SERVER['HTTP_REFERER']; // where did the post submission come from?
// if there's a valid referrer, and it's not the default log-in screen
if ( !empty($referrer) && !strstr($referrer,'wp-login') && !strstr($referrer,'wp-admin') ) {
wp_redirect( $referrer . '?login=failed' ); // let's append some information (login=failed) to the URL for the theme to use
exit;
}
}
If you just want to remove the shake, you can use this piece of code in your functions.php file which will stop the shake.
function my_login_head() {
remove_action('login_head', 'wp_shake_js', 12);
}
add_action('login_head', 'my_login_head');
This last suggestion is just based on a user accessing the wp-login.php page and then kicking them back to your custom login page.
function redirect_login_page() {
$login_page = home_url( '/login/' ); // CHANGE THIS TO YOUR PAGE URL
$page_viewed = basename($_SERVER['REQUEST_URI']);
if( $page_viewed == "wp-login.php" && $_SERVER['REQUEST_METHOD'] == 'GET') {
wp_redirect($login_page);
exit;
}
}
add_action('init','redirect_login_page');

Categories