Last active
September 21, 2021 08:03
-
-
Save verygoodplugins/2ca014a1a96c8c54358682ae37f03b00 to your computer and use it in GitHub Desktop.
Updates a wpf_logins_streak field each time a user logs in on two consecutive days
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function wpf_track_login_streak( $meta_id, $user_id, $meta_key, $meta_value ) { | |
if ( 'wpf_last_login' === $meta_key ) { // this runs every time the wpf_last_login field is about to be updated. | |
$prev_value = get_user_meta( $user_id, 'wpf_last_login', true ); // get the previous last login timestamp. | |
$prev_value = floor( absint( $prev_value ) / DAY_IN_SECONDS ); // Convert to days since Jan 1st 1970. | |
$meta_value = floor( absint( $meta_value ) / DAY_IN_SECONDS ) ; // Convert to days since Jan 1st 1970. | |
if ( ( $prev_value + 1 ) === $meta_value ) { | |
// If the user's last login was on the previous day. | |
$streak = get_user_meta( $user_id, 'wpf_logins_streak', true ); // get the current streak. | |
if ( empty( $streak ) ) { | |
$streak = 0; // if this is the first time, start with 0. | |
} | |
$streak++; // add 1 to the streak. | |
} elseif ( ( $prev_value + 1 ) > $meta_value ) { | |
// If for some reason the last login was today, don't do anything. | |
return; | |
} elseif ( ( $prev_value + 1 ) < $meta_value ) { | |
// If the previous login was before yesterday, reset the streak. | |
$streak = 1; | |
} | |
update_user_meta( $user_id, 'wpf_logins_streak', $streak ); // save the new streak to the database. | |
wp_fusion()->user->push_user_meta( $user_id, array( 'wpf_logins_streak' => $streak ) ); // sync it to the CRM. | |
} | |
} | |
add_action( 'update_user_meta', 'wpf_track_login_streak', 10, 4 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment