Execute a code snippet only for administrators

When you’re dealing with the code which alters the behavior of your WordPress powered website, more often than not, you’re executing the code for everyone on the side. But sometimes, you need to make things work only for you and the other administrators on the site. And you can do that very easily by checking for user capabilities.

In some code snippets that you can find on our site, we have already included the check for admins, but in this article, we will give you the simple code which can help you modify any snippet which you want to execute for admins only.

Execute a code for administrators only:

if ( current_user_can( 'manage_options' ) ) {
//Enter the code here

This condition checks for user’s capabilities and if that user can manage options, i.e. if that user is the admin of the site, the code will be executed. Otherwise, the code won’t run.

Instead of defining the capability, you can write the role name in statement:

if ( current_user_can( 'administrator' ) ) {
//Enter the code here

Since you’re checking for roles or capabilities here, you can see that administrator isn’t the only available one for the check. You can use the same code for checking if a user has any other role or capability and execute the code only for that type of a user. While there are only six standard users roles, it isn’t hard to decide which one you want to include in the condition; but if you want to check for a capability, be sure to learn more about them and see which users have which capabilities so that you can tailor the code to your needs.

Similarly, you can allow only admins to have the access to the wp-admin page.

Start Blog Book


This guide is an introduction to mastering the art of blogging. It provides easy to follow steps to start, maintain, and grow your blog.

Read the guide

Leave a Reply

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