Woocommerce 如何在管理员 post 编辑页面中获取产品的类别 ID
Woocommerce how to get categories ids of a product in the admin post edit page
我正在尝试限制特定类别的产品针对特定用户角色进行编辑。知道如何在 ...wp-admin/post.php?post=1702&action=edit
中获取产品的类别 ID 吗?
到目前为止,这是我的代码:
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);
您可以使用 get_the_terms
函数获取当前 post 的类别,然后获取它们的 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
上进行测试并且工作正常。