Custom username color for logged in users

Hi,
I was trying to have custom css for logged in users (to change their color name to green), but I can’t figure out how to do it.
I tried these ways:

  1. using plugins, but I didn’t get the desired result;
  2. custom css through “body.logged-in”, but it only refers to the current user;
  3. using the fucntion “is_user_logged_in()” , but also this refers only to the current user;
  4. using “wp_login” and “wp_logout” hooks, but they don’t fire.

The last way I thought should work, but adding this simple code to a snippet or to the functions.php, nothing happens:

add_action('wp_login', 'update_login_status_in',10,2);

function update_login_status_in($user_login,$user){
  	echo "<script type='text/javascript'>console.log('logged_in')</script>";
}

If I hook the init function instead, it works.

So, my first question is if is there another way to have custom css for all the logged in users (not only the current user)?
The second question is why the wp_login and wp_logout hooks don’t work?

Thank you in advance.

P.S. I have the HivePress Social Login plugin active and i don’t know if it can interfere with the hooks.

Sorry, there’s no simple code snippet for this - this would require a custom implementation. I recommend using any of the available “show online users” plugins for WordPress, and depending on how the plugin stores the online user status, you can then add a custom PHP snippet to set the link color, or override specific templates parts.

1 Like

Ok, thank you.

It wasn’t easy especially because I’m not an expert programmer, but I managed to get what I wanted.
I created a snippet that allows me to change the color of a seller’s name if it is online (the color is only changed on the seller’s page).
I also share the code for other users, consider that I am not a programmer and that the code is probably not very elegant. Any suggestions for improvement will be welcome.

function maUpdateUsers(){
	//get the total number of users
	$usersNumber=get_user_count();
	
	//retrive the current user ID
	$user=wp_get_current_user();
	$maUserID = $user->ID;
	//echo '<script type="text/javascript">console.log("'.$maUserID.'")</script>';
	
	//set the transient name and expiration time
	$transientName = 'maTransient' ; //transient name
	$maExpiration = 30*60; //expiration time (in seconds) 
	

	// get the transient
	$maUsersArray = get_transient($transientName);

	// check if the current user needs to update his online status;
	// status no need to update if user exist in the list
	// and if his "last activity" was less than 15 minutes ago  
	$no_need_to_update = isset($maUsersArray[$maUserID]) && $maUsersArray[$maUserID] >  (time() - (15 * 60));

	// update the list if needed
	if (!$no_need_to_update) {
	  $maUsersArray[$maUserID] = time();
	  set_transient($transientName, $maUsersArray, $maExpiration); // 30 mins 
	}
	
	//current user checkpoints
	//$maActualUserStatus=get_transient($transientName)[$maUserID];
	//$maUserName= get_user_by('id', $maUserID)->display_name;
	//$maVendorUrl= 'https://meshaffair.com/vendor/'."$maUserName";
	//echo '<script type="text/javascript">console.log("'.$maUserID.'")</script>';
	//echo '<script type="text/javascript">console.log("'.$maActualUserStatus.'")</script>';
	//echo '<script type="text/javascript">console.log("'.$maUserName.'")</script>';

	//get the current url
	global $wp;
	$wp->parse_request();
	$maCurrentUrl=add_query_arg( $_SERVER['QUERY_STRING'], '', home_url( $wp->request ) );
	//echo '<script type="text/javascript">console.log("'.$maCurrentUrl.'")</script>';//current url checkpoint
		
	//this part only runs on vendor pages
	//if the current page belongs to a vendor which is online the vendor's name becomes green
	if(str_contains($maCurrentUrl,'vendor')){
	$maDeltaTime = (time() - (15 * 60));//variable to check if the user was updated less than 15 minutes before current time
		//edit user name colors
		for ($i = 1; $i <= $usersNumber; ++$i){ //loop through users IDs
			$maUserStatus = $maUsersArray[$i];
			$maUserName= strtolower(get_user_by('id', $i)->display_name);
			$maVendorUrl= 'https://meshaffair.com/vendor/'."$maUserName";
			
			if($maUserStatus!=null && $maUserStatus > $maDeltaTime && $maCurrentUrl==$maVendorUrl){ //check if the user is online and if the actual page is vendor's page
				?>
				<style>
					.hp-vendor__name{
						color:#15cd72
					}$deltaTime
				</style>
				<?php
			}else {

			}

		} 
	
	}
	
}

add_action('init','maUpdateUsers');
2 Likes

If this works, halleluja to you. :blush: I will have to try this later.

I have been looking for a way to indicate if the vendor is online, and when the vendor was last seen. This would probably be possible with what you have provided, with some twerking? :face_with_monocle:

1 Like

Hi, if you add the above code inside a snippet it would work also in your website.
I think you should just change this:

> $maVendorUrl= 'https://meshaffair.com/vendor/'."$maUserName";
to
$maVendorUrl= 'your site name/vendor/'."$maUserName";

Also note that I use the prefix “ma” before variables which you can change as you want.
The snippet will run every time a user loads a page (because the function is hooked to the wordpress init hook) storing its activity as time within the transient.
The transient is an array of all users last activities time. After 30 minutes the whole array will be reset. You can change time variables within the script (they all must be expressed in seconds).
With this snippet, if a user loads a page of a vendor which is online, the vendor’s name will appear green, if the vendor is offline the name will be the default color.
To add “last seen” field I think is possible but I didn’t test it. Perhaps you can add a custom field to the vendors (which is already possible) and hook an hivepress action like hivepress/v1/models/{model_name}/update_{field_name}.
Here you can find a list of hivepress hooks and filters: Home | HivePress Hook Reference

I want to specify that there are sellers for whom the snippet doesn’t work at the moment.
This code compares the link of the current page with a string composed of the union of two strings: “yourHomePage/vendor/” + “vendor’s name”.
If the user’s name contains special characters such as a period, the actual link to the current page will not match the composed link. This is because the real slug is corrected and contains no special characters. The only thing that the current snippet intercepts is the presence of uppercase in the username, these are all changed to lowercase.

Thanks for sharing! The code seems to be ok, using transients is probably the best way to cache online user IDs. It can be simplified, but it should work fine in any case.

1 Like

Thank you :smile:
Anyway, if in the future you will develop an extension I will buy it. I would like very much to have a green dot badge for all online users.

Thanks, we’ll try to add more real-time features to the HivePress core.

1 Like