Skip to content

Instantly share code, notes, and snippets.

@timelsass
Created November 10, 2018 02:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timelsass/87b24de86a9cce6633bbc55ed4213a5f to your computer and use it in GitHub Desktop.
Save timelsass/87b24de86a9cce6633bbc55ed4213a5f to your computer and use it in GitHub Desktop.
Gives an example of how to allow editor role access to use siteimprove plugin.
<?php
/**
* Plugin Name: WPSE318816 Editor Access
* Description: Gives an example of how to allow editor role access to use siteimprove plugin. See https://wordpress.stackexchange.com/questions/318816/adding-menu-item-to-wordpress-admin-bar-for-editors-to-edit-one-plugins-setting.
* Plugin URI: https://gist.github.com/timelsass/87b24de86a9cce6633bbc55ed4213a5f
* Author: Tim Elsass
* Author URI: tim.ph
*/
// Checks if the current user is an editor role.
function wpse_318816_get_current_user_role() {
if ( is_user_logged_in() ) {
$user = wp_get_current_user();
return in_array( 'editor', $user->roles );
}
}
// Adds the siteimprove menu for the editor role's capability.
function wpse_318816_add_editor_menu() {
if ( wpse_318816_get_current_user_role() ) {
add_menu_page(
'Siteimprove Plugin',
'Siteimprove',
'edit_others_pages',
'siteimprove',
'Siteimprove_Admin_Settings::siteimprove_settings_form'
);
}
}
add_action( 'admin_init', 'wpse_318816_add_editor_menu' );
// Remaps edit capability to the user role.
function wpse_318816_add_editor_cap( $caps = array(), $cap = '', $user_id = 0, $args = array() ) {
global $pagenow;
if ( $cap !== 'manage_options' ) {
return $caps;
}
// Remove the filter to prevent resursive loops.
remove_filter( 'map_meta_cap', 'wpse_318816_add_editor_cap', 11 );
// Abort for admin.
if ( current_user_can( 'administrator' ) ) {
return $caps;
}
// Only do the following stuff if the user is the admin.
if ( wpse_318816_get_current_user_role() ) {
// Check if you're on the adminpage for siteimprove.
if ( ( $pagenow === 'admin.php' && $_GET['page'] === 'siteimprove' ) ||
// Check if you're submitting the token request form.
( $pagenow === 'options.php' && $_POST['option_page'] === 'siteimprove' ) ) {
// Set caps to edit_others_pages for the editor role.
$caps = array( 'edit_others_pages' );
// Re-add the filter.
add_filter( 'map_meta_cap', 'wpse_318816_add_editor_cap', 11, 4 );
// Remove the menu page as we are remapping manage_options to edit_others_pages.
remove_menu_page( 'siteimprove' );
}
}
return $caps;
}
add_filter( 'map_meta_cap', 'wpse_318816_add_editor_cap', 11, 4 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment