簡體   English   中英

Wordpress wp_get_current_user() 沒有顯示結果

[英]Wordpress wp_get_current_user() not showing result

我只是在測試一些 PHP 以嘗試找出用戶具有的角色,因為我想嘗試執行以下操作:

foreach($current_user->roles as $key => $value){
    if($value == ''){
        $npl= true;
    }
}

如果沒有選擇用戶角色,基本上將$npl更新$npl true。

下面的代碼只在它應該向我展示更多時才返回Array

<?php

include 'wp-blog-header.php';

$current_user = wp_get_current_user();
$user_id = $current_user->ID;
$user = new WP_User( $user_id );

echo "id:" . $current_user;

        foreach($current_user->roles as $key => $value){
            if($value == ''){
                echo "yes";
            }
            else {
                echo "no";
            }
        }

print_r(array_values($user->roles));

?>

數組

我已經嘗試在幾個階段使其工作,但早期顯示 id 也沒有顯示任何內容

編輯

我什至試過:

<?php

include '../wp-blog-header.php';
include '../includes/wp-load.php';
include_once('../wp-config.php');

$current_user = wp_get_current_user();
$user_id = $current_user->ID;

echo 'Username: ' . $current_user->user_login . '<br />';
echo 'User email: ' . $current_user->user_email . '<br />';
echo 'User first name: ' . $current_user->user_firstname . '<br />';
echo 'User last name: ' . $current_user->user_lastname . '<br />';
echo 'User display name: ' . $current_user->display_name . '<br />';
echo 'User ID: ' . $current_user->ID . '<br />';

foreach($current_user->roles as $key => $value){
    if($value == ''){
        echo "yes" . '<br />';
    }
    else {
        echo "no" . '<br />';
    }
}

print_r(array_values($current_user->roles));

echo '<br />' . "The time is " . date("h:i:sa");

?>

include wp-load.php並且加載文件在 root 上。 所以請包括加載文件

要求/包含 wp-load.php 的最簡單方法

如果您想在 WordPress 安裝之外的 PHP 文件中使用 WordPress 功能,那么您需要包含 wp-load.php。 也許你可以稱之為“連接到 WordPress”。

也許您已經在使用某種相對路徑方法,例如:

但是,如果目錄更改,這可能會產生問題。 您需要一種干凈、動態的方式來獲取 wp-load.php。 所以這是最簡單的方法,只需兩行代碼(將其放在文件的最頂部):

<?php include '../../../wp-load.php'; ?>

簡短而甜蜜:)

免責聲明:這僅用於實驗和開發目的。 不建議在實時生產環境中冗余加載 WordPress。 但是,為什么?

你的代碼有錯誤試試這個:

<?php

include 'wp-blog-header.php';

$current_user = wp_get_current_user();
$user_id = $current_user->ID;
$user = new WP_User( $user_id );

echo "id:" . $user_id;

    foreach($current_user->roles as $key => $value){
        if($value == ''){
            echo "yes";
        }
        else {
            echo "no";
        }
    }

    print_r(array_values($current_user->roles));

  ?>

您直接調用$current_user ,它將數組作為輸出。

我收到了你的問題,因為還沒有人給你正確的答案,我有你要找的東西。 我最近在 WP API 上使用它,根據當前用戶是否具有適當的權限,為某些用戶提供合理的訪問權限。 這是我的代碼。

function check_user_role(){

global $ne;

//check current user capabilities to determin the role type he pocess
if (!current_user_can('activate_plugins')) {
    $ne =  "Subscriber";
} else {
    $ne =  "admintrator";
}

$infos = array(
    'role' => $ne
);

return $ne;
}

echo check_user_role();

我希望它會幫助你。 ☻☻☻☻

暫無
暫無

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

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