How to switch between two forms for visitor once admin logged in?

I have two forms (form1 and form2). Once the admin is logged in anywhere, all visitors (not logged in) to my WordPress site should see form1 on the page, otherwise they should see form2. I am using this code in a custom page template:

if ( current_user_can( 'author' ) || current_user_can( 'administrator' ) ) {    
    // show form1    
} else {   
    // show form2
}

This works fine, but only for the admin screen, not other users or visitors. How can I make this universal?

Topic switch admin forms Wordpress

Category Web


How many admins will you have? If you will only have a couple of them you can use WP_User_Meta_Session_Tokens to check for sessions based on specific user ID.

Something like

$sessions = new WP_User_Meta_Session_Tokens( $user_id );
$user_sessions = $sessions->get_sessions();

You could loop through all users and see if any admin are logged in but that would just cause higher load and queries on each page load (I do not recommend).

The only other thing I could think of was to have an option, say, total_logged_in_admins, and just hook into login and logout and increase/decrease admin count based on whether the user is an admin or not.

Then on your page just check the count of admins logged in


You need to check all online users and see if admin is logged-in or not.

With this plugin you can get all online users.

https://wordpress.org/plugins/wp-useronline/

Can use a function to check if list includes admin or not. Based on that you can display forms.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.