Block posting to selected categories

Exclude category for role

Exclude category for role

Block posting to the list of selected categories on per role base – is it possible? If you wish to limit your WordPress blog authors or users with custom created role from posting to some categories only, you can do it with piece of PHP code below (read entire post to get it.).

Just copy it and paste it into your active theme functions.php file (wp-content/themes/your-theme/functions.php) insert ID of categories to block. You can get ID of category at Categories page. Move mouse over ‘Edit’ link of selected category and look on the link at the bottom of your browser. Search ‘tag_ID=’ there. The number to the right of it is the category ID.
Congratulations! That’s all. You got it.

if (current_user_can('author')) {  // change 'author' role to your own if needed
  if (is_admin()) {
 
    function limit_categories_for_role($exclusions) {
 
      $cats_to_exclude = array(14, 30);  // insert you categories ID to exclude for entire role here
      foreach ($cats_to_exclude as $cat_id) {
        $exclusions .= " AND (t.term_id<>$cat_id)";
      }
 
      return $exclusions;
    }
 
    add_filter('list_terms_exclusions', 'limit_categories_for_role');
  }
}

In case you need to block for role ability to post into all categories except one, two or some small subset, and your categories list is large or extended too often, then other code will be more effective. We get full categories list for begin here, then we delete from it those categories, to which we plan to give access.

 if (current_user_can('author')) {	// change 'author' role to your own if needed
	if (is_admin()) {
 
		function limit_categories_for_role($exclusions) {
 
			remove_filter('list_terms_exclusions', 'limit_categories_for_role');  // delete our filter in order to avoid recursion when we call get_all_category_ids() function
			$cats_to_exclude = get_all_category_ids();	// take full categories list from WordPress
			add_filter('list_terms_exclusions', 'limit_categories_for_role');  // restore our filter
			$cats_to_save = array(21, 25); // insert here categories ID, to which you wish to give access for this role
			$cats_to_exclude = array_diff($cats_to_exclude, $cats_to_save); // delete ID, to which we give access, from the full categories list
			$cats_to_exclude = '('. implode( ',', $cats_to_exclude) .')'; // build WHERE expression for SQL-select command
			$exclusions = " AND (t.term_id not IN $cats_to_exclude)";
 
			return $exclusions;
		}
 
		add_filter('list_terms_exclusions', 'limit_categories_for_role');
	}
 }

Tags: , ,