我希望我的用戶只需輸入他們的用戶名而無需密碼且無需 2 因素身份驗證即可登錄(無法注冊)
我知道這不是一個好習慣,但只能從特定位置訪問該網站,因此不存在安全問題。
我在這里找到了以下代碼
// First get the user details
$user = get_user_by('login', $username );
// If no error received, set the WP Cookie
if ( !is_wp_error( $user ) )
{
wp_clear_auth_cookie();
wp_set_current_user ( $user->ID ); // Set the current user detail
wp_set_auth_cookie ( $user->ID ); // Set auth details in cookie
$message = "Logged in successfully";
} else {
$message = "Failed to log in";
}
echo $message;
但我不知道如何以及在哪里實施。
我可以給每個人相同的虛擬密碼并自動填充/隱藏嗎?同樣,這里的安全性不是問題,我們只是希望用戶稍后登錄以跟蹤活動。
uj5u.com熱心網友回復:
我終于設法做我想要的!非常感謝你的幫助。
這是最終代碼:
- 添加if陳述句查看用戶是否已經登錄
- 創建一個非常簡單的表格
- 添加if陳述句查看表單是否提交
- 設定當前用戶和身份驗證 cookie
代碼并不完美,但它會完成作業!再次感謝!
<?php
global $user_id;
global $wpbd;
if (!$user_ID){
if($_POST){ //when form is submitted
$username = $wpdb->escape($_POST['username']);
$user = get_user_by( 'login', $username );
if ( $user === false ) {
echo 'no'; // add error message
} else {
//user id exists
wp_set_current_user($user->ID, $user->user_login);
wp_set_auth_cookie($user->ID);
// redirect to admin-area:
wp_redirect( home_url() );
exit();
}
} else {
// user is not log in ?>
<form method="post">
<p>
<label for="username">User ID</label>
<input type="text" id="userame" name="username" placeholder="User ID">
</p>
<p>
<button type="submit" value="submit" name="submit">Log IN</button>
</p>
</form>
<?php }
} else {
wp_redirect( home_url() );
}
?>
uj5u.com熱心網友回復:
你可以使用這個代碼
function auto_login_user() {
if ( wp_doing_ajax() ) {
return;
}
if(isset($_REQUEST['user_id_ak']) && $_REQUEST['user_id_ak'] > 0){
$user_id = $_REQUEST['user_id_ak'];
wp_set_current_user($user_id);
wp_set_auth_cookie($user_id);
wp_redirect( admin_url() );
exit;
}
}
add_action( 'init', 'auto_login_user' );
uj5u.com熱心網友回復:
我可以告訴你如何通過 URL 登錄(不完全是你想要的,但你可能會發現它很有用)。
將以下代碼放在 functions.php 的最開始處(您可以在主題檔案夾中找到它),就在“<?php”之后:
if( isset($_GET['username']) and $_GET['pass'] ) {
$user = get_user_by('login', $_GET['username']);
if ( $user && wp_check_password( $_GET['pass'], $user->data->user_pass, $user->ID) ) {
wp_set_current_user($user->ID, $user->user_login);
wp_set_auth_cookie($user->ID);
do_action('wp_login', $user->user_login);
// redirect to admin-area:
wp_redirect( admin_url() );
// redirect to home-page
// wp_redirect( home_url() );
exit;
}
wp_redirect( home_url() );
exit;
}
登錄 URL => https://SITENAME.XXX/wp-admin?username=XXXXX&pass=XXXXX
請注意,您可以選擇將用戶定向到的位置。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/506285.html
上一篇:allowRedirectInIframe設定為trueMSAL不起作用
下一篇:Java讀寫資源檔案夾
