Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check the first login wordpress

Tags:

wordpress

I need create something like this:

if is first login show: [something]

if is second login show: [something2]

if is third login show: [something3]

because I need to show different messages inside a post on each time login, is it possible?

like image 561
Juliane k Avatar asked Mar 06 '23 06:03

Juliane k


1 Answers

This is certainly doable, you could try and track cookies, but that will get really tedious and inaccurate over the long run.

You'll probably want to track & increment a custom User Meta field using the update_user_meta() function tied to the wp_login hook which fires after a user logs in.

Also, you'll need to read up on the add_shortcode() function to output the content you want, but something like this will be more than enough to get you started. It tracks how many times they log in, and anywhere you put [login_content] - it will output the appropriate text according to the value of $login_amount.

add_action( 'wp_login', 'track_user_logins', 10, 2 );
function track_user_logins( $user_login, $user ){
    if( $login_amount = get_user_meta( $user->id, 'login_amount', true ) ){
        // They've Logged In Before, increment existing total by 1
        update_user_meta( $user->id, 'login_amount', ++$login_amount );
    } else {
        // First Login, set it to 1
        update_user_meta( $user->id, 'login_amount', 1 );
    }
}

add_shortcode( 'login_content', 'login_content' );
function login_content( $atts ){
    if( is_user_logged_in() ){
        // Get current total amount of logins (should be at least 1)
        $login_amount = get_user_meta( get_current_user_id(), 'login_amount', true );

        // return content based on how many times they've logged in.
        if( $login_amount == 1 ){
            return 'Welcome, this is your first time here!';
        } else if( $login_amount == 2 ){
            return 'Welcome back, second timer!';
        } else if( $login_amount == 3 ){
            return 'Welcome back, third timer!';
        } else {
            return "Geez, you have logged in a lot, $login_amount times in fact...";
        }
    }
}

You should just be able to put this in your functions.php file.

like image 187
Xhynk Avatar answered May 05 '23 01:05

Xhynk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!