php WordPress -用户上次登录日期短代码不工作

abithluo  于 2023-04-28  发布在  PHP
关注(0)|答案(3)|浏览(88)

我有这个简码,它应该显示最后登录日期给用户。我发现的问题是,所有其他用户都在查看我的最后登录日期,而不是他们的日期。
我的简码有什么问题吗?

// Last Login Shortcode
function user_last_login( $user_login, $user ) {
update_user_meta( $user->ID, 'last_login', date( current_time( 'timestamp' )) );
}
add_action( 'wp_login', 'user_last_login', 10, 2 );

function lastlogin() {  
$last_login = get_the_author_meta('last_login');
$the_login_date = date('F j, Y, g:i a', $last_login);
return $the_login_date;
}
add_shortcode('lastlogin','lastlogin');
vjhs03f7

vjhs03f71#

我自己找到了解决办法。我张贴的代码为任何人谁将在同样的问题,因为我。我还扩展了代码,现在你可以同时获得当前登录日期和当前登录之前的最后一次访问日期。
我不太擅长这些东西,我在php,wordpress和代码方面相对较新。我邀请任何人清理代码,并尽可能使其更短和更容易。

  • 将下面的代码放在函数中。php子主题文件。*
// Function that set last login
add_action('wp_login', 'set_last_login', 0, 2);
function set_last_login($login, $user) {
    $user = get_user_by('login',$login);
    $time = current_time( 'timestamp' );
    $last_login = get_user_meta( $user->ID, '_last_login', 'true' );
    if(!$last_login) {
    update_user_meta( $user->ID, '_last_login', $time );
    } else {
    update_user_meta( $user->ID, '_last_login_prev', $last_login );
    update_user_meta( $user->ID, '_last_login', $time );
    }
}

// Function that get last login
function get_last_login($user_id, $prev = null) {
    $last_login = get_user_meta($user_id);
    $time = current_time( 'timestamp' );
    if(isset($last_login['_last_login_prev'][0]) && $prev) {
        $last_login = get_user_meta($user_id, '_last_login_prev', 'true' );
    } else if(isset($last_login['_last_login'][0])){
        $last_login = get_user_meta($user_id, '_last_login', 'true' );
    } else {
        update_user_meta( $user_id, '_last_login', $time );
        $last_login = $last_login['_last_login'][0];
    }
    return $last_login;
}

// Shortcode 1
function last_login_date() {
    global $current_user;
    echo '<p>Last login date: '. date("j M Y - H:i", get_last_login ($current_user->ID, true)) . '</p>';
}
add_shortcode('lastlogin', 'last_login_date');

// Shortcode 2
function current_login_date() {
    global $current_user;
    echo '<p>Current: Login date: '. date("j M Y - H:i", get_last_login($current_user->ID)). '</p>';
}
add_shortcode('currentlogin', 'current_login_date');

1.如果您想显示上次登录日期(而不是当前登录日期),请使用[lastlogin]
2.如果您想在每次新登录时显示当前日期,请使用[currentlogin]
如何更改日期和时间格式:您可以更改短码1和短码2。编辑"j M Y - H:i",这里有一些有用的信息https://www.php.net/manual/en/datetime.format.php

抱歉英语说得不好

mum43rcc

mum43rcc2#

谢谢你的澄清。看起来你用错了功能。
get_the_author_meta()检索当前帖子的作者的请求数据,因此如果您使用该函数,所有用户都将显示帖子作者的日期。
因此,在您的情况下,您需要使用get_user_meta()
你可以在这里找到信息:https://developer.wordpress.org/reference/functions/get_user_meta/
尝试解决方案,如果它不起作用,我们将进一步挖掘。

fwzugrvs

fwzugrvs3#

我在2022年4月14日试过了。显示2022年3月30日

相关问题