Skip to content

Instantly share code, notes, and snippets.

@bappi-d-great
Created July 30, 2014 20:32
Show Gist options
  • Save bappi-d-great/654c709174aafff6388b to your computer and use it in GitHub Desktop.
Save bappi-d-great/654c709174aafff6388b to your computer and use it in GitHub Desktop.
Let author to add categories but categories and tags are not accessible restricted by some keywords
<?php
// Adding capabilities in admin init
add_action( 'admin_init', 'add_author_cap' );
function add_author_cap() {
// Get current user's role
global $current_user;
$user_roles = $current_user->roles;
$user_role = array_shift($user_roles);
if( $user_role == 'author' ) {
// Removing the category and tag admin pages for authors
remove_submenu_page( 'edit.php', 'edit-tags.php?taxonomy=category' );
remove_submenu_page( 'edit.php', 'edit-tags.php?taxonomy=post_tag' );
}
// Adding capabilities for authors
$role = get_role( 'author' );
$role->add_cap( 'manage_categories' );
}
add_action( 'admin_footer', 'check_cat_keys' );
function check_cat_keys() {
// Get role of the user
global $current_user;
$user_roles = $current_user->roles;
$user_role = array_shift($user_roles);
if( $user_role == 'author' ) {
?>
<script type="text/javascript">
jQuery(function($){
// This is the array of restricted keywords. Add as many as you want. Items in this array can't be added by the author
var keywords = new Array( 'test', 'hey', 'bad' );
$('#category-add-submit').click(function(e){
var newCat = $('#newcategory').val();
if(inArray(newCat, keywords)) {
e.preventDefault();
// Alert message for the author when he tries to add a restricted category keyword
alert( 'You can\'t use this word as category name.' );
return false;
}else{
return true;
}
});
// Function for comparing two arrays
function arrayCompare(a1, a2) {
if (a1.length != a2.length) return false;
var length = a2.length;
for (var i = 0; i < length; i++) {
if (a1[i] !== a2[i]) return false;
}
return true;
}
// Check if an element is available in an array
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(typeof haystack[i] == 'object') {
if(arrayCompare(haystack[i], needle)) return true;
} else {
if(haystack[i] == needle) return true;
}
}
return false;
}
});
</script>
<?php
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment