Last active
June 26, 2023 15:36
-
-
Save oguzhancoskun/5f04a1758cf7924bda96da1a30ba111e to your computer and use it in GitHub Desktop.
wordpress_role_permission_management
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
This script generate custom editors for specific categories, editors just list, view and publish to specific categories | |
*/ | |
function create_custom_editor_roles($editor_categories) { | |
foreach ($editor_categories as $editor => $category) { | |
$role_slug = sanitize_title($editor) . '_editor'; | |
$role_name = ucwords($editor) . ' Editor'; | |
add_role( | |
$role_slug, | |
$role_name, | |
array( | |
'read' => true, | |
'publish_posts' => true, | |
) | |
); | |
add_custom_capabilities_to_editor($role_slug); | |
add_filter_posts_by_category($role_slug, $category); | |
} | |
} | |
add_action('init', function() { | |
$editor_categories = array( | |
'editor1' => 'tag1', | |
'editor2' => 'tag2', | |
); | |
create_custom_editor_roles($editor_categories); | |
}); | |
function add_custom_capabilities_to_editor($role_slug) { | |
$role = get_role($role_slug); | |
$role->add_cap('edit_posts'); | |
$role->add_cap('edit_others_posts'); | |
$role->add_cap('delete_posts'); | |
} | |
function add_filter_posts_by_category($role_slug, $category) { | |
add_action('pre_get_posts', function($query) use ($role_slug, $category) { | |
if (is_admin() && current_user_can($role_slug)) { | |
if ($query->is_main_query()) { | |
$categories = get_terms(array( | |
'taxonomy' => 'category', | |
'parent' => get_cat_ID($category), | |
'fields' => 'ids', | |
'hide_empty' => false, | |
)); | |
$query->set('cat', $categories); | |
$query->set('post_status', 'pending'); | |
} | |
} | |
}); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment