Wordpress Disable Page if user not logged in - php

I have a page 'account' where I want users to be able to edit their profile.
But how do I disable the page for users who are not logged in?
Maybe with: !is_user_logged_in ?
They should not be able to access the page. Maybe get redirected to login page.

Add this code in your Function.php file.
using template_redirect action hook
function template_redirect_fn()
{
if(is_page (Page ID, title, slug of account page ) && !is_user_logged_in ())
{
$loginUrl = home_url('/login-page/');
wp_redirect($loginUrl);
exit();
}
}
add_action( 'template_redirect', 'template_redirect_fn' );
is_page() is check page is account [you can pass the account page id or page title or page slug ]
is_user_logged_in() is check user is login or not return (bool) True if user is logged in, false if not logged in.

You can do this flowing way.
if( !is_user_logged_in ) {
$loginUrl = home_url('/login-page/');
echo '<script>window.location.href = "'.$loginUrl.'";</script>';
}

Related

Why does is_user_logged_in() return false after redirect from another site?

I am developing a WordPress site that redirects to an external payment gateway after a user registers for the site. After the user makes a payment the user is redirected to a page to complete their sign up.
Here is the code used for the redirect:
$login_data = array();
$login_data['user_login'] = $email;
$login_data['user_password'] = $password;
$login_data['remember'] = true;
$user = wp_signon($login_data);
if(!is_wp_error($user)){
wp_set_current_user( $user->ID, $email );
wp_set_auth_cookie( $user->ID, true, false );
wp_redirect("https://another_payment_gateway.com");
exit;
}
The user is redirected and fills out the payment form. Upon success the user is redirected to a landing page. If they are not logged in they are shown a dialog for non logged in users. Here is the code on that page:
if(is_user_logged_in()){
$user = wp_get_current_user();
//code for logged in users
}else{
//message for non logged in users
}
If I go to the account page it is shown that the user is logged in. But when redirected from a different site is_user_logged_in() returns false. Any insight into this issue would be much appreciated.
add_action( 'loop_start', 'your_function' );
function your_function() {
if ( is_user_logged_in() ) {
echo '<li id="text-2" class="hide">';
} else {
echo '<li id="text-2">';
}
}
Please check with the above hook , will that work for logged-in and non-logged-in user.

How to redirect after login to BuddyPress profile in WordPress

I run WordPress 5.1.1 with BuddyPress plugin.
Basically what I want to do is, redirect the user from custom login link to their profile page in BuddyPress.
I have read and check almost all codes provided on Stackoverflow for my similar query but non one has worked on my site.
The only code worked it's below but it has one problem for my site settings and setup.
function bp_help_redirect_to_profile(){
global $bp;
if( is_user_logged_in() && is_front_page() ) {
bp_core_redirect( get_option('home') . '/members/' .
bp_core_get_username( bp_loggedin_user_id() ) . '/profile' );
}
}
add_action( 'get_header', 'bp_help_redirect_to_profile',1);
The problem is, when I want to redirect on homepage of the website it's keep redirecting me on the BuddyPress profile. Categories and post sections are loading correctly.
So, what i need is, when the login flow redirect user on their BuddyPress profile page, after when user hit the homepage of the site to load the homepage of the site and not, the BuddyPress.
I hope someone can help and tweak the function in this way.
Thank you
add_filter( 'bp_login_redirect', 'bpdev_redirect_to_profile', 11, 3 );
function bpdev_redirect_to_profile( $redirect_to_calculated, $redirect_url_specified, $user )
{
if( empty( $redirect_to_calculated ) )
$redirect_to_calculated = admin_url();
//if the user is not site admin,redirect to his/her profile
if( isset( $user->ID) && ! is_super_admin( $user->ID ) )
return bp_core_get_user_domain( $user->ID );
else
return $redirect_to_calculated; /*if site admin or not logged in,do not do
anything much*/
}
Tested Code put in your active theme function file
You can use wp_login action for that. Please check following example. bp_core_get_user_domain() will fetch the profile URL and after successful login user will be redirected to that profile URL.
function wpso_take_to_profile( $user_login, $user ) {
if ( function_exists( 'bp_core_get_user_domain' ) ) {
$url = bp_core_get_user_domain( $user->ID );
wp_redirect( $url );
die();
}
}
add_action('wp_login', 'wpso_take_to_profile', 10, 2);

Redirect to an other URL if logged in or logged out

I'm working on a web site on wordpress.
I have a link on my homepage called "SALE" , I would like people if they are logged in to access to the page ...../my-account/vendre/ and if they are not to the create account page" ..../register/
I tried this but doesn't work:
add_action( 'admin_init', 'redirect_non_logged_users_to_specific_page' );
function redirect_non_logged_users_to_specific_page() {
if ( !is_user_logged_in() && is_page('my-account_vendre') &&
$_SERVER['PHP_SELF'] != '/wp-admin/admin-ajax.php' ) {
wp_redirect( 'http://www.example.dev/register' );
exit;
}
}
Any idea ?
Create $_SESSION variable if user is logged like $_SESSION['isloged'] and then you can check in if this variable is set. If it is set the show the button with redirect to ...../my-account/vendre/ else redirect to ..../register/

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;
}
}

Wordpress: On login send to pages list rather than dashboard

Is there a function that will allow you to change where you get redirected to once logged in?
I'm logging into the standard Wordpress login form which redirects you to the dashboard, is there a way to change it so you get redirected to the pages list?
It's important that I'm not editing core WP files (although easy, it's asking for trouble!) and doing this via a function.
This isn't any kind of front end log in, it's all backend just redirecting the standard WP login screen from the dashboard to the pages list - wp-admin/edit.php?post_type=page (as I don't like the info displayed on the dashboard).
Add this to your theme functions.php:
function my_login_redirect( $redirect_to, $request, $user ){
//is there a user to check?
global $user;
if( isset( $user->roles ) && is_array( $user->roles ) ) {
//check for admins
if( in_array( "administrator", $user->roles ) ) {
// redirect them to the default place
return home_url(); //admin redirect url
} else {
return admin_url( 'edit.php?post_type=page' ); //user redirect url
}
}
else {
return $redirect_to;
}
}
add_filter("login_redirect", "my_login_redirect", 10, 3);
This will redirect the user back to the homepage once logged in. With the above you can redirect administrators to a seperate location (dashboard if need be) and then the rest of your users to your custom url.

Categories