[WooCommerce] 後台整理術:開放商店管理員(Shop Manager)修改使用者角色(role)

本篇文章更新時間:2022/08/10
如有資訊過時或語誤之處,歡迎使用 Contact 功能通知。
一介資男的 LINE 社群開站囉!歡迎入群聊聊~
如果本站內容對你有幫助,歡迎使用 BFX Pay 加密貨幣新台幣 贊助支持。


WooCommerce 在 3.4.6 的更新中加上了一個安全性修正,調整商店管理員針對網站上使用者角色權限的新增與修改方式。

會發現這個問題也是因為先前使用 editable_roles 這個 Hook 可以做到調整。但安裝了 WooCommerce 外掛後就無法。經查詢後才發現是被 woocommerce_shop_manager_editable_roles 這個 Hook 給影響。

延伸閱讀: [WooCommerce] 後台整理術:開放修改作者、編輯等使用者帳號設定

實際使用方式如下:

function mxp_shop_manager_role_edit_capabilities($roles) {
    $roles   = array();
    $roles[] = 'customer_alt';
    $roles[] = 'customer';
    return $roles;
};
add_filter('woocommerce_shop_manager_editable_roles', 'mxp_shop_manager_role_edit_capabilities', 99, 1);

透過程式碼片段去複寫設定來選擇要開放哪些角色。

如果沒有安裝 WooCommerce 的情況下要控制某個角色的「角色編輯」權限就還是 editable_roles 的 Hook,範例如下:

function mxp_editable_roles($role) {
    $user          = wp_get_current_user();
    $allowed_roles = array('administrator');
    if (!array_intersect($allowed_roles, $user->roles) && strpos(get_current_screen()->id,'user')!==false) {
        $role     = wp_roles()->roles;
        $new_role = array();
        // $new_role['author'] = $role['author'];
        $new_role['customer_alt'] = $role['customer_alt'];
        $new_role['customer']     = $role['customer'];
        return $new_role;
    } else {
        return $role;
    }
}
add_filter('editable_roles', 'mxp_editable_roles', 99, 1);

這寫法的意思是「除了管理員外的其他角色,於建立或選擇角色權限時,僅能看到 customer customer_alt 這兩個。

整理後台給業主不只是簡化他學習使用 WordPress 的門檻,再來也是要有效避免操作失誤導致網站陷入一些不可控制風險,造成其他成本延伸。


Share:

作者: Chun

資訊愛好人士。主張「人人都該為了偷懶而進步」。期許自己成為斜槓到變進度條 100% 的年輕人。[///////////____36%_________]

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *


文章
Filter
Apply Filters
Mastodon