I'm trying to restrict products from a certain category from editing for a specific user role. Any idea how to get the catgories IDs of a product in ...wp-admin/post.php?post=1702&action=edit
?
Here's my code so far:
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);
My Answer:
You can get the category IDs of a product in the admin post edit page by using the following code snippet:
php
global $post;
// Get the product ID
$product_id = $post->ID;
// Get the product categories
$product_categories = wp_get_post_terms($product_id, 'product_cat');
// Loop through the categories and get the IDs
$category_ids = array();
foreach ($product_categories as $category) {
$category_ids[] = $category->term_id;
}
// Now you have an array of category IDs for the product
print_r($category_ids);
You can add this code to your theme's functions.php file or create a custom plugin to restrict product editing based on category IDs for specific user roles.
Rate this post
5 of 5 based on 1564 votesComments