Create the Class
The first thing we need to do is create the scaffolding for a plugin. Let’s begin by creating the class, the construtor, and an init method:
There are actually very few lines of code here applicable to access control. The first highlighted line is the protected class variable
$defaultOptionVals. This variable initially holds the default user roles which have access to the plugin and the plugin configuration options page.
The second highlighted line of code above does a quick check for
is_admin() to ensure that the user is actually logged in to the admin. It then makes a call to
$this->hasPluginAccess(). The hasPluginAccess method is a very important piece to the puzzle; restricting the access to the admin backend.
Creating the Role Based Restriction Method
The actions performed by the method are:
- merge the default allowable administrator role with any selected roles from the plugin options page
- grab the currently logged in user’s role(s)
- compare the user-defined access control list (ACL) against the currently logged in user’s role
- return a boolean value based on the comparison
Let’s take a look at that function now:
The only remaining step is to create the plugin options page to allow for user restriction by selecting roles from a multi-select dropdown. We’ve already named our method
admin_menu in the
init() method above. Let’s create the page.
Create the Options Page
The options page must retrieve all available user roles from WordPress to populate the dropdown. It also compares these values against the currently selected options; falling back on the default administrator option. The method also handles creating the form, error handling, form submission, and storing the updated option values.
Yup, you’re done already. We’ve covered all of the code necessary for you to implement a basic access control list for your plugin. This simple tutorial could easily be expanded to add multiple multi-select dropdowns to restrict role access to different parts of your plugin. The majority of the actual plugin code was left out as it would convolute the actual tutorial. You can download the JinX plugin with full sourcecode from it’s WordPress plugin page. You may also view the full source code as a github gist without a download. Here’s a quick summary of what we have accomplished with the above code:
- We’ve added an options page allowing selection of user roles.
- We’ve added handling to retrieve the currently logged in user’s role.
- We’ve added handling to the init method to only call core plugin functions for display if the logged in user has one of the selected roles from the config page.