How can i check if user is logged in for the first time on site?
If it is, i want to show him a message...
Can someone help me?
Thank you!
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this communityHow can i check if user is logged in for the first time on site?
If it is, i want to show him a message...
Can someone help me?
Thank you!
** UPDATE **
As suggested by oknate, using hook_user_login:
function hook_user_login(&$edit, $account)
{
if(!$account->access)
{
drupal_set_message(t('This is your first login. Welcome!'));
}
}
** Original less optimal method **
You can use hook_init() in D7, and check if they have a value for last access:
function hook_init()
{
global $user;
$first_login = db_query('SELECT 1 FROM {users} WHERE uid = :uid AND access = 0', array(':uid' => $user->uid))->fetchField();
if($first_login)
{
drupal_set_message(t('This is your first login. Welcome!'));
}
}
In both Drupal 7 and 8, there is hook_user_login, where you can can check whether the current user has accessed the site before, but the parameters are slightly different.
Drupal 7 version:
function mymodule_user_login(&$edit, $account) {
if ($account->access == 0) {
drupal_set_message(t('This is your first login. Welcome!'));
}
}
Drupal 8 version:
function mymodule_user_login($account) {
if (!$account->getLastAccessedTime()) {
drupal_set_message(t('This is your first login. Welcome!'));
}
}
hook_user_login in Drupal 8.
For D7 you can use rules to achieve the same,
Here is the sample rule,
{ "rules_first_login_test" : {
"LABEL" : "First login test",
"PLUGIN" : "rule",
"REQUIRES" : [ "rules" ],
"USES VARIABLES" : { "user" : { "label" : "User", "type" : "user" } },
"IF" : [ { "data_is_empty" : { "data" : [ "user:last-access" ] } } ],
"DO" : [ { "drupal_message" : { "message" : "True" } } ]
}
}
Import this rule and modify according to your need.
You can check the more information here.