Why WordPress developers often get the is_admin function wrong

Let me first say that I’m guilty. For “performance reasons” I’m always careful to only run functions in their appropriate area of WordPress – so, something only used in the admin area will be checked via the use of is_admin. Only if this is true will I then run that code. It makes sense.

But for plugins there is no performance improvement.

Registering a shortcode simply adds it to an internal array – it’s only if the shortcode is used that any impact on performance will occur. Therefore you gain nothing by not just registering the shortcode everywhere.

Some developers will also use is_admin in an attempt to provide a shortcode from being used within an ajax request. To quote the Codex

is_admin() will return true when trying to make an ajax request (both front-end and back-end requests)

So, whether in the admin or not, shortcodes will still work within ajax. The true way to check for ajax use is…

if ( defined( 'DOING_AJAX' ) && DOING_AJAX )

I’ll consider myself educated and will be updating my plugins now to run in all situations. But I’m not alone in my thinking and many very popular plugins do the same – only registering plugins when not in Admin.

For this reason it should never be assumed that, if checking in admin for a registered plugin (the global array $shortcode_tags holds all of the registered plugins and which function they call) that it will give you an accurate answer. Sadly, I’ve already come across one plugin that does assume this and uses the results to delete all shortcodes from a user’s blog that have not been registered. A dangerous assumption but, thankfully, one that is not currently in the WordPress.org repository. And, yes, that means if you run this it will purge all of my plugins’ shortcodes from your site!

Talk to me!

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from David Artiss

Subscribe now to keep reading and get access to the full archive.

Continue reading