Run PHP Only If the User Is a WordPress Administrator
Use this WordPress PHP function so your code stays visible to you alone, the site administrator.
Working on PHP code that only the site’s administrator can see, when that administrator is also the developer, lets you keep working on a live site without any other visitor ever noticing. It’s handy, for example, while you double-check that everything works before going public, without having to build the code on a separate staging version first, which would mean a lot more juggling.
FAQ
What's the difference between current_user_can('manage_options') and is_admin() in WordPress?
They have nothing to do with each other. current_user_can('manage_options') checks that the current user actually holds administrator rights, which is exactly what we want here. is_admin() only checks whether you're inside the dashboard (the back office), not who the person is. This is a common trap: don't mix them up.
Where should I put this code: functions.php or a snippets plugin like Code Snippets?
Both work. Your active theme's functions.php is the most direct route, but your code vanishes the moment you switch themes. A plugin like Code Snippets keeps it theme-independent and makes it easy to enable or disable safely. On a live site, I personally prefer the plugin, it's the safer bet.
Will the protected code run for the Editor or Author roles?
No. The 'manage_options' capability is granted by default only to administrators. An Editor or an Author doesn't have it, so your conditional block ignores them just like any other visitor. If you wanted to target those roles too, you'd test a capability they share, such as 'edit_posts'.
How do I test this code without being logged in as admin (to see what a visitor sees)?
The simplest way: open your site in a private/incognito window where you're not logged in. You'll see exactly what an anonymous visitor sees. You can also log out, or use a second browser. A role-switcher plugin lets you simulate an Editor or Author without logging out either.
Comments