Skip to content

Instantly share code, notes, and snippets.

@ajaydsouza
Created December 15, 2024 19:53
Show Gist options
  • Save ajaydsouza/d250240fe6578eef301b377e08d4863c to your computer and use it in GitHub Desktop.
Save ajaydsouza/d250240fe6578eef301b377e08d4863c to your computer and use it in GitHub Desktop.
Control WZKB user roles
<?php
/**
* Knowledge Base Custom Capabilities and Access Control
*/
function wzkb_set_knowledge_base_capabilities() {
// Roles that should have full access to Knowledge Base
$full_access_roles = [
'administrator',
'editor'
];
// Roles that should have read-only access
$read_only_roles = [
'contributor',
'author'
];
// Define custom capabilities for the Knowledge Base
$capabilities = [
'read_wz_knowledgebase',
'edit_wz_knowledgebase',
'delete_wz_knowledgebase',
'publish_wz_knowledgebase',
'edit_wz_knowledgebases',
'edit_others_wz_knowledgebases'
];
// Add full access capabilities
foreach ($full_access_roles as $role_name) {
$role = get_role($role_name);
if ($role) {
foreach ($capabilities as $cap) {
$role->add_cap($cap, true);
}
}
}
// Add read-only capabilities
foreach ($read_only_roles as $role_name) {
$role = get_role($role_name);
if ($role) {
$role->add_cap('read_wz_knowledgebase', true);
}
}
}
add_action('init', 'wzkb_set_knowledge_base_capabilities', 999);
/**
* Modify post type registration to use custom capabilities
*/
function wzkb_modify_knowledge_base_capabilities($args) {
if ($args['name'] === 'wz_knowledgebase') {
$args['capabilities'] = [
'read_post' => 'read_wz_knowledgebase',
'edit_post' => 'edit_wz_knowledgebase',
'delete_post' => 'delete_wz_knowledgebase',
'edit_posts' => 'edit_wz_knowledgebases',
'edit_others_posts' => 'edit_others_wz_knowledgebases',
'publish_posts' => 'publish_wz_knowledgebase',
'read_private_posts' => 'read_private_wz_knowledgebases'
];
}
return $args;
}
add_filter('wzkb_post_type_args', 'wzkb_modify_knowledge_base_capabilities');
/**
* Additional access control for frontend and admin
*/
function wzkb_knowledge_base_access_control() {
global $post;
// Check for knowledge base post type
if (is_singular('wz_knowledgebase') || is_post_type_archive('wz_knowledgebase')) {
// If user cannot read the knowledge base, redirect
if (!current_user_can('read_wz_knowledgebase')) {
wp_redirect(home_url());
exit;
}
}
// Additional admin area restrictions
if (is_admin()) {
$screen = get_current_screen();
if ($screen->post_type === 'wz_knowledgebase') {
// Prevent users without proper capabilities from accessing certain actions
if (!current_user_can('edit_wz_knowledgebase')) {
wp_die(__('You do not have sufficient permissions to access this page.', 'knowledgebase'));
}
}
}
}
add_action('template_redirect', 'wzkb_knowledge_base_access_control');
add_action('admin_init', 'wzkb_knowledge_base_access_control');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment