我正在嘗試限制某個類別的產品針對特定用戶角色進行編輯。知道如何獲取產品的類別 ID...wp-admin/post.php?post=1702&action=edit嗎?
到目前為止,這是我的代碼:
function restrict_edit_if_in_manufacturing_cat($post){
global $pagenow, $post_type;
// Targeting admin edit single product screen
if ($pagenow === 'post.php' && $post_type === 'product') {
// Get current user
$user = wp_get_current_user();
// Roles
$roles = (array) $user->roles;
// Roles to check
$roles_to_check = array('shop_manager'); // several can be added, separated by a comma
// Compare
$compare = array_diff($roles, $roles_to_check);
// Result is empty
if (empty($compare)) {
// $category_ids = ...Get Category IDs here...
// If 458 is in the category id list die
if (strpos($category_ids, '458') !== false) {
wp_die('cheatn');
} else {
// do something if needed
}
}
}
}
add_action('pre_get_posts', 'restrict_edit_if_in_manufacturing_cat', 10, 1);
uj5u.com熱心網友回復:
您可以使用get_the_terms函式來獲取當前帖子的類別,然后獲取它們的 id,如下所示:
add_action('pre_get_posts', 'restrict_edit_if_in_manufacturing_cat');
function restrict_edit_if_in_manufacturing_cat($post)
{
global $pagenow, $post_type;
if ($pagenow === 'post.php' && $post_type === 'product')
{
$current_user = wp_get_current_user();
$user_roles = $current_user->roles;
if (in_array("shop_manager", $user_roles))
{
$categories_for_the_current_post = get_the_terms($_GET['post'], 'product_cat');
$categories_ids = array();
foreach ($categories_for_the_current_post as $category_object) {
array_push($categories_ids, $category_object->term_id);
}
if (in_array('458', $categories_ids))
{
wp_die('cheatn');
} else {
// do something if needed
}
}
}
}
此代碼段已在標準 woo 安裝上進行了測驗,5.7.1并且運行良好。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/384912.html
標籤:php WordPress的 求购 wordpress-admin
上一篇:用手走過放氣
