WordPress - Check if user is logged in - php

I am fairly new to WordPress. On my homepage I have a navigation bar which I only want to show to people who are logged in as users.
In my header.php the function is_logged_in doesn't seem to work.
I want to place a condition in my header.php file to check if the user has logged in (and then display the navigation).
Any advice would be helpful.

Use the is_user_logged_in function:
if ( is_user_logged_in() ) {
// your code for logged in user
} else {
// your code for logged out user
}

Example: Display different output depending on whether the user is logged in or not.
<?php
if ( is_user_logged_in() ) {
echo 'Welcome, registered user!';
} else {
echo 'Welcome, visitor!';
}
?>

Try following code that worked fine for me
global $current_user;
get_currentuserinfo();
Then, use following code to check whether user has logged in or not.
if ($current_user->ID == '') {
//show nothing to user
}
else {
//write code to show menu here
}

get_current_user_id() will return the current user id (an integer), or will return 0 if the user is not logged in.
if (get_current_user_id()) {
// display navbar here
}
More details here get_current_user_id().

This problem is from the lazy update data request of Chrome.
At the first time you go to homepage. Chrome request with empty data. Then you go to the login page and logged in. When you back home page Chrome lazy to update the cookie data request because this domain is the same with the first time you access.
Solution:
Add parameter for home url. That helps Chrome realizes that this request need to update cookie to call to the server.
add at dashboard page
<?php
$track = '?track='.uniqid();
?>
<img src="/img/logo.svg">

I think that.
When guest is launching page, but Admin is not logged in we don`t show something, for example the Chat.
add_action('init', 'chat_status');
function chat_status(){
if( get_option('admin_logged') === 1) { echo "<style>.chat{display:block;}</style>";}
else { echo "<style>.chat{display:none;}</style>";}
}
add_action('wp_login', function(){
if( wp_get_current_user()->roles[0] == 'administrator' ) update_option('admin_logged', 1);
});
add_action('wp_logout', function(){
if( wp_get_current_user()->roles[0] == 'administrator' ) update_option('admin_logged', 0);
});

Related

Wordpress autologin link only works when clicked twice or reloaded

I have a Wordpress site and I have setup an autologin PHP script that checks for a KEY value in the URL which corresponds to a user in a table and then logs that user into the site. I have this because I have a user who requested to be able to login to the site by just clicking a link and not having to enter in a username and password each time.
I have gotten it to work, the weird thing is though it only works some of the time. When a user clicks the link it takes them to a landing page for that user.
The autologin link looks like this: https://mywebsite.org/home/autologin.php?key=54321
Sometimes when the link is clicked it just sits at that url, other times it properly logs in and redirects to the landing page url which is: https://mywebsite.org/library-portal-landing-page/
When the link just stalls and sits on the autologin URL the page will redirect and load if the autologin link is reloaded and I am not sure why it needs reloaded sometimes and other times it just works.
Here is my autologin.php PHP script:
<?php
require_once("wp-load.php");
global $wpdb;
// Check if user is already logged in, redirect to account if true
if (!is_user_logged_in()) {
// Check if the key is set and not emtpy
if(isset($_GET['key']) && !empty($_GET['key'])){
// Sanitize the received key to prevent SQL Injections
$received_key = sanitize_text_field($_GET['key']);
// Find the username from the database using the received key
$get_username = $wpdb->get_var($wpdb->prepare("SELECT avatar FROM wp_autologin WHERE random_key = %s", $received_key ) );
// Check if query returned a result, throw an error if false
if(!empty($get_username)){
// Get user info from username then save it to a variable
$user = get_user_by('login', $get_username );
// Get the user id then set the login cookies to the browser
wp_set_auth_cookie($user->ID);
// To make sure that the login cookies are already set, we double check.
foreach($_COOKIE as $name => $value) {
// Find the cookie with prefix starting with "wordpress_logged_in_"
if(substr($name, 0, strlen('wordpress_logged_in_')) == 'wordpress_logged_in_') {
// Redirect to account page if the login cookie is already set.
wp_redirect( home_url('/library-portal-landing-page/') );
} else {
// If NOT set, we loop the URL until login cookie gets set to the browser
wp_redirect( home_url('/home/autologin/?key=' . $received_key) );
}
}
} else {
echo 'Invalid Authentication Key';
}
} else {
wp_redirect( home_url() );
}
} else {
wp_redirect( home_url('/library-portal-landing-page/') );
exit;
}
?>
I got it to work by adding a javascript redirect to run after a few seconds which did the trick, I added this after the end of the PHP file:
<script>
setTimeout(function () {
window.location.href = "https://mywebsite.org/library-portal-landing-page/";
}, 2000);
</script>

Redirect a user to the page they were trying to access after login in Wordpress

I have a page that is restricted to logged in users (say it's called '/authed-page'). When a non-authenticated user visits this page they are prompted to click a button to login and they are then taken to the login url: '/login'
Now after they login I want them to get redirected to the page they had been trying to visit, '/authed-url', but I can't figure out how to do this!
Things I've tried:
1) Declaring a function redirect_to_authed_url in my functions.php file like this
function redirect_to_authed_url( $redirect_to, $request, $user ) {
return "/post-a-job";
}
Then in the template for authed-url.php when I detect the user isn't logged in I do this:
<?php add_filter( 'login_redirect', 'redirect_to_authed_url', 10, 3 ); ?>
However this doesn't work I think because the user presses a button which generates another http request which sends them to the '/login' url which means the redirect filter is lost.
2) Setting a cookie when someone visits '/authed-url' and they are not logged in called 'redirect_url'. Then I declare this in my theme's functions.php file
function redirect_request( $redirect_to, $request, $user ) {
if (isset($_COOKIE['login_redirect']) && strpos($_COOKIE['login_redirect'], 'http') === false) {
$redirect_url = $_COOKIE['login_redirect'];
unset $_COOKIE['login_redirect'];
return $redirect_url;
} else {
return('/');
}
}
This doesn't seem to work because I can't figure out where to set the cookie. I keep getting the warning:
WARNING: CANNOT MODIFY HEADER INFORMATION - HEADERS ALREADY SENT
I feel like I must be missing something obvious. This should be a pretty common requirement no? Any ideas?
You are able to append a URL encoded redirect_to variable to the login URL to get it to redirect after login.
For example:
http://www.example.com/wp-login.php?redirect_to=http%3A%2F%2Fwww.example.com%2Fauthed-url
That URL will redirect you to /authed-url after login.
you can try this function to check user logging or not.
<?php
if( is_user_logged_in() ) {
echo 'your function for logging user';
}else{
echo 'your function for not logging user';
}
?>

Check from which page the user is coming to the current page in wordpress

I want to check if a user comes from a specific page to the current page.
e.g
if (user comes from /bingo.php)
{ wp_redirect( /newpage.php );exit; }
else { // do nothing };
thank you :)
Without completely answering your question, I'd say you could look into $_SERVER['HTTP_REFERER']. This contains the previous page your user came from. Please note that this is not always set.
Here is my code for my case:
if (!is_user_logged_in() ) {
$icamefrom = $_SERVER['HTTP_REFERER'];
if ( $icamefrom == 'the_site_you_want_to_check') { wp_redirect( '/signup' ); exit; };
}

Conditional page for logged user (Member Only Page)

I want to make my wordpress site hidden or restricted from guest user. Only the the registered member will see my pages, if they are not registered then they will be redirected in login page/ registration page.
When i am tried to use some plugin to do that then all of my pages restricted and there had option to exclude only one page (login page). But i guest cant register there. Because all of the page restricted excluding loging page. SO thats a problem.
Now i think i can use custom code something like that
<?php
if ( is_user_logged_in() ) {
echo 'Welcome, registered user!';} else { echo 'You have no rights to access this page. Please log in or a href=\"#\">register</a> now to access that page';
}
?>
But how can i set a function , "If logged in then full page will open other wise show a text"
If you want to hide the content, then you can use the_content hook to change the page content for not loggedin user.
add_filter('the_content', 'restricted_content');
function restricted_content($content)
{
if( !is_user_logged_in()
{
$content = 'You have no rights to access this page...blah blah..';
}
return $content;
}
Now, if the login/registration is a General WordPress Page created using WP Admin, you can either exclude it by id, name or slug.
function restricted_content($content)
{
if( !is_user_logged_in() && ! is_page('login') && ! is_page('registration') // an id or name can be passed also
{
$content = 'You have no rights to access this page...blah blah..';
}
return $content;
}

Redirect to referer url in codeigniter

In messaging system of my project when you get a message from a user you a email alert saying that the another user has sent a message to view the message click here (i.e the url of message) So if the user is not logged in to system he gets redirect to login page and after login it should get back to the referer url. I have made a basecontoller in core folder and extending the CI_controller the authenticating code is as follows.
function authenticate($type = 'user')
{
if($type == 'user')
{
if($this->user_id)
{
// user is logged in. check for permissions now
}
else
{
// user isnt logged in. store the referrer URL in a var.
if(isset($_SERVER['HTTP_REFERER']))
{
$redirect_to = str_replace(base_url(),'',$_SERVER['HTTP_REFERER']);
}
else
{
$redirect_to = $this->uri->uri_string();
}
redirect('user/login?redirect='.$redirect_to);
exit;
}
}
if($type == 'admin')
{
if($this->session->userdata('admin_id') && $this->session->userdata('user_type') ==5)
{
// Admin is logged in
}
else
{
redirect('admin/login');
exit;
}
}
}
The referer url is "http://example.com/project/pm/view_conversation?id=11"
now the problem is I am getting referer url till view_conversation and not able to get the id part.
Any suggestion ?
Thank you.
This can help:
CI 2+
https://www.codeigniter.com/userguide2/libraries/user_agent.html
CI 3+
http://www.codeigniter.com/userguide3/libraries/user_agent.html
Below solution is for Codeigniter version 3
$this->load->library('user_agent');
if ($this->agent->is_referral())
{
echo $this->agent->referrer();
}
UPDATE: interesting and useful information on how to obtain referrer information with the same user_agent library
https://www.tutorialandexample.com/user-agent-class/
How about just
redirect($_SERVER['HTTP_REFERER']);
Using php's $_SERVER global variable.
This worked for me!
Put that code in your Login Controler
function index() {
$this->load->library('user_agent'); // load user agent library
//Set session for the referrer url
$this->session->set_userdata('referrer_url', $this->agent->referrer() );
}
After Login Redirection Code
// user is authenticated if referrer is there
if( $this->session->userdata('referrer_url') ) {
//Store in a variable so that can unset the session
$redirect_back = $this->session->userdata('referrer_url');
$this->session->unset_userdata('referrer_url');
redirect( $redirect_back );
}
Because you have double question mark in the url, the browser ignores the url part after the second one. Use urlencode for you redirect part, like so:
redirect('user/login?redirect='.urlencode($redirect_to));
I've tested it out and it works this way.
By default CI is configured to ignore the query part of the URL (the part after the '?').
See: http://codeigniter.com/user_guide/general/urls.html

Categories