With web applications and powerful websites, there will be times you want to only show a Meta Box or Meta Field to a particular user role or capability. For an Order Management system you may want your customers to see certain fields, while your employees can see them all. Or maybe you want Administrators and Editors to be able to leave notes on a post that no one else can see. Well, Piklist makes it easy to do just that.
In this tutorial, we will show you how you can easily control who sees your data.
- First let’s build a Meta Box using our base tutorial. Once completed you should have a working Meta Box with three fields.
- Piklist allows you to show/hide either the entire Meta Box, or each individual field… with just one line of code.
Show entire Meta Box by Capability or Role
In the comment block at the top of your meta box file (demo-metabox.php if you used the base tutorial), we are going to add the “Capability” parameter. NOTE: This parameter can take a “capability” or “role”. To use a role, add the following line of code:
Now, this meta box will only show for the editor… and ONLY someone assigned as an editor. This is NOT the “minimum” role, this is THE role, which means it will not show for the administrator. It will only show for the role: editor.
If you want it to show for an editor and above (i.e. administrator), then use a capability instead. Use a capability like “edit_pages“, which is given to an Editor and and Administrator. So you code would look like this:
If you started with our base tutorial, then your full header code snippet would look like this:
<?php /* Title: My Demo Meta Box Post Type: post Capability: edit_pages */
Show a Meta Field by Capability or Role
Again, we start with the base tutorial. In this example, let’s show the Text Box field to only Editors. The code we use is very similar to what we discussed above, it’s just formatted for an array:
,'capability' => 'editor'
Again, this will only show the field for an Editor… no other role, including Administrator. Just Editor. If we want to use capabilities instead, like “edit_pages“, we would use this code:
,'capability' => 'edit_pages'
The entire snippet for this field, would look like this:
piklist('field', array( 'type' => 'text' ,'scope' => 'post_meta' ,'field' => 'demo_text' ,'label' => 'Text box' ,'description' => 'Field Description' ,'value' => 'Default text' ,'capability' => 'edit_pages' ,'attributes' => array( 'class' => 'text' ) ,'position' => 'wrap' ));