WordPress插件開發(fā)教程手冊 — 用戶、角色和能力

本教程詳細(xì)介紹了WordPress插件開發(fā)中用戶、角色和能力的管理方法。文章講解了如何通過wp_create_user()和wp_insert_user()函數(shù)添加和更新用戶,并解釋了最小能力原則。適合開發(fā)者學(xué)習(xí)如何自定義角色和權(quán)限,優(yōu)化WordPress用戶管理功能。

WordPress 用戶存儲在 wp_user 數(shù)據(jù)表中。

什么是用戶?

WordPress 中,每個用戶至少有一個用戶名、密碼和電子郵件地址。一旦創(chuàng)建了用戶賬戶,用戶就可以的登錄后臺來訪問 WordPress 的功能和數(shù)據(jù)。

角色和能力

每個用戶都會被分配一個角色,每個角色都會有一些能力。我們可以自定義一組能力來創(chuàng)建一個新角色。還可以創(chuàng)建自定義能力,然后分配給現(xiàn)有角色或新角色。在 WordPress 中,開發(fā)人員可以利用用戶角色來限制用戶是否可以執(zhí)行一組操作。

最小能力原則

WordPress 遵守最少能力原則,即只賦予用戶執(zhí)行操作所需要的必不可少的能力的做法。

操作 WordPress 用戶

添加用戶

如果需要添加用戶,我們可以使用 wp_create_user() 或 wp_insert_user() 函數(shù)。

wp_create_user() 使用用戶名,密碼和電子郵件參數(shù)創(chuàng)建用戶,而 wp_insert_user() 接受描述用戶及其屬性的數(shù)組或?qū)ο蟆?/p>

創(chuàng)建用戶

wp_create_user(
   string $username,
   string $password,
   string $email = ''
);

上面的示例可以讓我們創(chuàng)建一個新用戶。

該函數(shù)使用 wp_slash() 轉(zhuǎn)義參數(shù),使用 compact() 函數(shù)把上面的值創(chuàng)建為數(shù)組,然后使用 wp_insert_user() 函數(shù)將用戶數(shù)據(jù)插入到到數(shù)據(jù)庫中。

有關(guān)該函數(shù)參數(shù)的完整說明,請參閱關(guān)于 wp_create_user() 的函數(shù)參考。

創(chuàng)建用戶的示例

// check if the username is taken
$user_id = username_exists($user_name);

// check that the email address does not belong to a registered user
if (!$user_id && email_exists($user_email) === false) {
   // create a random password
   $random_password = wp_generate_password(
      $length = 12,
      $include_standard_special_chars = false
   );
   // create the user
   $user_id = wp_create_user(
      $user_name,
      $random_password,
      $user_email
   );
}

插入用戶

wp_insert_user(
   array|object|WP_User $userdata
);
此函數(shù)為大部分預(yù)定義屬性添加了 Filter 鉤子,創(chuàng)建用戶的時候(參數(shù)中沒有 ID),執(zhí)行 user_register Action 鉤子,更新用戶的時候(參數(shù)中有用戶 ID),執(zhí)行 profile_update Action 鉤子。

有關(guān)該函數(shù)參數(shù)的完整說明,請參閱 wp_insert_user() 函數(shù)的參考文檔。

插入用戶示例

下面的示例演示了插入用戶,并添加用戶資料的過程。

$username = $_POST['username'];
$password = $_POST['password'];
$website = $_POST['website'];
$user_data = [
   'user_login' => $username,
   'user_pass'  => $password,
   'user_url'   => $website,
];

$user_id = wp_insert_user($user_data);

// success
if (!is_wp_error($user_id)) {
   echo 'User created: ' . $user_id;
}

更新用戶

wp_update_user(
   mixed $userdata
);

更新數(shù)據(jù)庫中的某個用戶時,更新數(shù)據(jù)通過 $userdata 數(shù)據(jù)/對象中傳遞。如果需要更新用戶元數(shù)據(jù),使用 update_user_meta() 。

如果更新了某個用戶的密碼,Cookies 會被清除,該用戶需要重新登錄。

有關(guān)該函數(shù)參數(shù)的完整說明,請參閱 wp_update_user() 函數(shù)的參考文檔。

更新用戶示例

下面是更新用戶網(wǎng)址字段的示例代碼。

$user_id = 1;
$website = 'https://wordpress.org';

$user_id = wp_update_user(
   [
      'ID'       => $user_id,
      'user_url' => $website,
   ]
);

if (is_wp_error($user_id)) {
   // error
} else {
   // success
}

刪除用戶

wp_delete_user(
   int $id,
   int $reassign = null
);

刪除用戶時,我們可以選擇把用戶創(chuàng)建的內(nèi)容重新分配給其他用戶。

當(dāng)用戶被刪除后,deleted_user 鉤子會被執(zhí)行。
如果沒有設(shè)置$reassign參數(shù),或者該參數(shù)不是一個有效的用戶ID,被刪除用戶創(chuàng)建的所有內(nèi)容也會被刪除。

有關(guān)該函數(shù)參數(shù)的完整說明,請參閱 wp_delete_user() 函數(shù)的參考文檔。

操作用戶元數(shù)據(jù)

簡介

WordPress 的 user 數(shù)據(jù)中僅包含用戶的基本信息。

在 WordPress 4.7 中,用戶數(shù)據(jù)表僅包含:ID,user_login,user_pass,user_nicename,user_email,user_url,user_registered,user_activation_key,user_status,display_name。

為了存儲附加數(shù)據(jù),WordPress 引入了 wp_usermeta 數(shù)據(jù)表,我們可以在這個數(shù)據(jù)表中存儲任意多的用戶數(shù)據(jù)。這個表使用用戶 ID 字段和 wp_user 數(shù)據(jù)表關(guān)聯(lián)。

操作用戶元數(shù)據(jù)

在 WordPress 中,有兩種方法可以操作用戶元數(shù)據(jù)。

  1. 通過個人資料編輯界面中的表單
  2. 通過程序的方式使用相關(guān)函數(shù)操作

通過表單字段

使用表單字段更新用戶元數(shù)據(jù)的方法適用于可以訪問 WordPress 管理界面的情況,我們可以在用戶資料編輯界面查看和編輯用戶資料。

在我們深入研究一個示例之前,我們先了解一下這個過程中涉及的鉤子以及為什么會有這些鉤子非常重要。

edit_user_profile 鉤子

只要用戶編輯了自己的配置文件,就會觸發(fā)此鉤子,請記住,沒有編輯自己個人資料的用戶不會觸發(fā)這個鉤子。

show_user_profile 鉤子

只要用戶編輯了其他人的用戶資料,就會觸發(fā)此鉤子。請記住,沒有編輯其他人資料的用戶不會觸發(fā)此鉤子。

示例表單

下面的例子中,我們將在用戶資料編輯界面添加一個生日字段,并在用戶資料更新時將其保存到數(shù)據(jù)庫中。

<?php
/**
 * The field on the editing screens.
 *
 * @param $user WP_User user object
 */
function wporg_usermeta_form_field_birthday($user)
{
   ?>
   <h3>It's Your Birthday</h3>
   <table class=form-table>
      <tr>
         <th>
            <label for=birthday>Birthday</label>
         </th>
         <td>
            <input type=date
                   class=regular-text ltr
                   id=birthday
                   name=birthday
                   value=<?= esc_attr(get_user_meta($user->ID, 'birthday', true)); ?>
                   title=Please use YYYY-MM-DD as the date format.
                   pattern=(19[0-9][0-9]|20[0-9][0-9])-(1[0-2]|0[1-9])-(3[01]|[21][0-9]|0[1-9])
                   required>
            <p class=description>
               Please enter your birthday date.
            </p>
         </td>
      </tr>
   </table>
   <?php
}
 
/**
 * The save action.
 *
 * @param $user_id int the ID of the current user.
 *
 * @return bool Meta ID if the key didn't exist, true on successful update, false on failure.
 */
function wporg_usermeta_form_field_birthday_update($user_id)
{
   // check that the current user have the capability to edit the $user_id
   if (!current_user_can('edit_user', $user_id)) {
      return false;
   }

   // create/update user meta for the $user_id
   return update_user_meta(
      $user_id,
      'birthday',
      $_POST['birthday']
   );
}
 
// add the field to user's own profile editing screen
add_action(
   'edit_user_profile',
   'wporg_usermeta_form_field_birthday'
);
 
// add the field to user profile editing screen
add_action(
   'show_user_profile',
   'wporg_usermeta_form_field_birthday'
);
 
// add the save action to user's own profile editing screen update
add_action(
   'personal_options_update',
   'wporg_usermeta_form_field_birthday_update'
);
 
// add the save action to user profile editing screen update
add_action(
   'edit_user_profile_update',
   'wporg_usermeta_form_field_birthday_update'
);

通過編程的方式

這種方法適合于我們構(gòu)建自定義用戶資料編輯界面,并打算禁止用戶訪問 WordPress 管理界面的情況。

可用于操作用戶元數(shù)據(jù)的函數(shù)是:add_user_meta()update_user_meta()delete_user_meta() 和 get_user_meta()

添加
add_user_meta(
   int $user_id,
    string $meta_key,
    mixed $meta_value,
    bool $unique = false
);

有關(guān)該函數(shù)參數(shù)的完整說明,請參閱 add_user_meta()  的函數(shù)參考。

更新
update_user_meta(
   int $user_id,
    string $meta_key,
    mixed $meta_value,
    mixed $prev_value = ''
);

有關(guān)該函數(shù)參數(shù)的完整說明,請參閱 update_user_meta()  的函數(shù)參考。

刪除
delete_user_meta(
   int $user_id,
    string $meta_key,
    mixed $meta_value = ''
);

有關(guān)該函數(shù)參數(shù)的完整說明,請參閱 delete_user_meta()  的函數(shù)參考。

獲取
get_user_meta(
   int $user_id,
    string $key = '',
    bool $single = false
);

有關(guān)該函數(shù)參數(shù)的完整說明,請參閱 get_user_meta() 的函數(shù)參考。

注意,如果僅傳遞 $user_id 參數(shù)給該函數(shù),該函數(shù)將獲取該用戶的所有元數(shù)據(jù)為一個關(guān)聯(lián)數(shù)組。

我們可以在主題或插件的任何地方顯示用戶元數(shù)據(jù)。

角色和能力

角色和能力是 WordPress 中比較重要的兩個概念,可以讓我們控制用戶權(quán)限。WordPress 將角色及其能力存儲在 wp_options 數(shù)據(jù)據(jù)表中的 user_roles 字段中。

角色

角色為用戶定義了一組能力,例如,用戶可以在儀表盤中看到什么和操作什么。

默認(rèn)情況下,WordPress 有 6 個角色。

  • 超級管理員
  • 管理員
  • 編輯
  • 作者
  • 投稿者
  • 訂閱用戶

我們可以添加自定義角色或刪除默認(rèn)角色。

添加角色

我們可以使用 add_role() 添加新角色并為其分配能力。

function wporg_simple_role() {
   add_role(
      'simple_role',
      'Simple Role',
      [
         'read'         => true,
         'edit_posts'   => true,
         'upload_files' => true,
      ]
   );
}

// add the simple_role
add_action( 'init', 'wporg_simple_role' );
在第一次調(diào)用 add_role() 之后,角色和他的能力將被存儲在數(shù)據(jù)庫中!我們無法控制該函數(shù)的調(diào)用順序,包括替換能力列表。
如果需要批量更改能力列表:使用 remove_role() 刪除角色,并使用 add_role() 添加新能力。只要能力和我們需要的不同,一定要這樣做,否則你會大大降低性能!

刪除角色

我們可以使用 remove_role() 刪除角色。

function wporg_simple_role_remove() {
   remove_role( 'simple_role' );
}

// remove the simple_role
add_action( 'init', 'wporg_simple_role_remove' );
第一次調(diào)用該函數(shù)后,角色及其能力將從數(shù)據(jù)庫中被刪除。
如果您要刪除默認(rèn)角色:我們建議不要刪除管理員和超級管理員角色!確保將代碼保留在插件/主題中,因?yàn)槲磥淼?WordPress 更新可能會再次添加這些角色。如果我們刪除了 Subscriber 這個 WordPress 角色,需要運(yùn)行 update_option(‘default_role’, YOUR_NEW_DEFAULT_ROLE) 設(shè)置新的默認(rèn)角色。

能力

能力定義了角色可以做什么,不可以做什么,如:編輯文章,發(fā)布文章等。

自定義文章類型可能需要一組特定的能力。

添加能力

我們可以為角色定義新能力。使用 get_role() 獲取角色對象,然后使用 add_cap() 方法為角色添加新能力。

function wporg_simple_role_caps() {
   // gets the simple_role role object
   $role = get_role( 'simple_role' );

   // add a new capability
   $role->add_cap( 'edit_others_posts', true );
}

// add simple_role capabilities, priority must be after the initial role definition
add_action( 'init', 'wporg_simple_role_caps', 11 );
我們可以將自定義能力添加到任何角色。在默認(rèn)的 WordPress 管理界面中,它們不起作用,但可用于自定義管理界面和前端區(qū)域。

刪除能力

我們可以從角色中移除某個能力。該實(shí)現(xiàn)類似于添加能力,不同之處在于使用的方法為 remove_cap() 。

使用角色和能力

獲取角色

我們可以通過 get_role() 函數(shù)獲取角色對象,包括它的所有能力。

get_role(
   string $role
);

使用 user_can() 函數(shù)判斷用戶能力

我們可以使用?user_can()?函數(shù)檢查用戶是否有指定的角色或能力。

user_can(
   int|object $user,
    string $capability
);
該函數(shù)有一個未公開的第三個參數(shù) $args,可以包含測試應(yīng)該執(zhí)行的對象。例如:傳遞文章ID以測試該特定文章的缺陷。

使用 current_user_can()  判斷當(dāng)前登錄用戶的能力

current_user_can()?是?user_can()?的封裝,使用當(dāng)前用戶對象作為?$user?參數(shù)。我們可以在前端或后端判斷當(dāng)前用戶的能力。

示例

下面是一個在模板文件中添加編輯鏈接的實(shí)例,如果用戶具有必要的能力,就顯示文章編輯鏈接:

if (current_user_can('edit_posts')) {
   edit_post_link('Edit', '<p>', '</p>');
}

多站點(diǎn)

在多站點(diǎn)中,使用 current_user_can_for_blog() 函數(shù)判斷當(dāng)前用戶是否在某個站點(diǎn)上具有某個能力。

current_user_can_for_blog(
   int $blog_id,
    string $capability
);

參考

WordPress 用戶角色和能力 參考文檔。

我們提供 WordPress主題和插件定制開發(fā)服務(wù)

本站長期承接 WordPress主題、插件、基于 WooCommerce 的商店商城開發(fā)業(yè)務(wù)。 我們有 10 年WordPress開發(fā)經(jīng)驗(yàn),如果你想 用WordPress開發(fā)網(wǎng)站, 請聯(lián)系微信: iwillhappy1314,或郵箱: [email protected] 咨詢。

發(fā)表回復(fù)

您的郵箱地址不會被公開。 必填項(xiàng)已用 * 標(biāo)注

*