簡體   English   中英

WordPress - 檢查用戶是否登錄

[英]WordPress - Check if user is logged in

我對 WordPress 還很陌生。 在我的主頁上,我有一個導航欄,我只想向以用戶身份登錄的人顯示。

在我的header.php ,函數is_logged_in似乎不起作用。

我想在我的header.php文件中放置一個條件來檢查用戶是否已登錄(然后顯示導航)。

任何意見將是有益的。

使用is_user_logged_in函數:

if ( is_user_logged_in() ) {
   // your code for logged in user 
} else {
   // your code for logged out user 
}

嘗試以下對我有用的代碼

global $current_user;
get_currentuserinfo();

然后,使用以下代碼檢查用戶是否已登錄。

if ($current_user->ID == '') { 
    //show nothing to user
}
else { 
    //write code to show menu here
}

get_current_user_id()將返回當前用戶 ID(整數),如果用戶未登錄,則返回 0。

if (get_current_user_id()) {
   // display navbar here
}

更多細節在這里get_current_user_id()

這個問題來自於Chrome的懶惰更新數據請求。 第一次進入主頁。 帶有空數據的 Chrome 請求。 然后你進入登錄頁面並登錄。當你回到主頁時Chrome懶得更新cookie數據請求,因為這個域和你第一次訪問時是一樣的。 解決方案:為主頁 url 添加參數。 這有助於 Chrome 意識到此請求需要更新 cookie 以調用服務器。

在儀表板頁面添加

<?php 
$track = '?track='.uniqid();
?>
<a href="<?= get_home_url(). $track ?>"> <img src="/img/logo.svg"></a>

示例:根據用戶是否登錄顯示不同的輸出。

<?php

if ( is_user_logged_in() ) {
    echo 'Welcome, registered user!';
} else {
    echo 'Welcome, visitor!';
}

?>

我覺得。 當來賓啟動頁面但管理員未登錄時,我們不會顯示某些內容,例如聊天。

add_action('init', 'chat_status');

function chat_status(){

    if( get_option('admin_logged') === 1) { echo "<style>.chat{display:block;}</style>";}
        else { echo "<style>.chat{display:none;}</style>";}

}



add_action('wp_login', function(){

    if( wp_get_current_user()->roles[0] == 'administrator' ) update_option('admin_logged', 1);
});


add_action('wp_logout', function(){
    if( wp_get_current_user()->roles[0] == 'administrator' ) update_option('admin_logged', 0);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM