Categories
CMS Mastering Development Wordpress

Enable a role named ‘backend_user’ to access my plugin pages

I am new to plugin development and I am fairly okay with development by following all the plugin development best practices set by WordPress Codex. Following code describes on how Role: Administrator of WordPress gains access to the plugin.

Administrator access to plugin in settings: SettingsApi.php

public function register()
    {
        if ( ! empty($this->admin_pages) || ! empty($this->admin_subpages)) {
            add_action( 'admin_menu', array( $this, 'addAdminMenu' ) );
        }
}
public function addSubPages( array $pages )
    {
        $this->admin_subpages = array_merge( $this->admin_subpages, $pages );

        return $this;
    }

    public function addAdminMenu()
    {
        foreach ( $this->admin_pages as $page ) {
            add_menu_page( $page['page_title'], $page['menu_title'], $page['capability'], $page['menu_slug'], $page['callback'], $page['icon_url'], $page['position'] );
        }

        foreach ( $this->admin_subpages as $page ) {
            add_submenu_page( $page['parent_slug'], $page['page_title'], $page['menu_title'], $page['capability'], $page['menu_slug'], $page['callback'] );
        }
    }

Adding a new role to user base of WordPress by following code while activation: Activate.php

$result = 
                add_role
                (
                    'backend_user',
                    __( 'Plugin Name Backend', 'testsite' ),
                    array(
                    'read'         => true,  // true allows this capability
                    'edit_posts'   => false,
                    'delete_posts' => false,
                )
                );

I am looking at how to set rights to the role backend_user to access plugin pages in my SettingApi.php. Also if there is any method that will enable backend_user to access my plugin pages in the WordPress login please suggest.

I Tried following function in SettingApi.php under register()

$user = wp_get_current_user();
            if ( in_array( 'backend_user', (array) $user->roles ) ) {

            add_action( 'admin_menu', array( $this, 'addAdminMenu' ) );
            }

Not working. Any help would be grateful.

Leave a Reply

Your email address will not be published. Required fields are marked *