I have noticed that some plugins such as Contact-form-7, Nextgen-gallery, possibly others, have an interesting anti-feature of not registering their shortcodes when is_admin()
is true.
The problematic thing is, if you want to generate some dynamic content (which may have shortcode) from ajax, and use the “correct” wp way of doing it, admin-ajax.php, it is impossible to not have WP_ADMIN be true. See the first lines of admin-ajax.php:
define( 'DOING_AJAX', true );
if ( ! defined( 'WP_ADMIN' ) ) {
define( 'WP_ADMIN', true );
}
Now, it seems there are PHP extensions that will let you un-set a defined constant (hacky), or there may be a way to mess with the undocumented WP_Screen system and $GLOBALS['current_screen']
to make is_admin()
function return false?? The most usable workaround seems to be posting to the page or the site root.
Is it common for plugins to register their shortcodes when is_admin()
is false? If so, I couldn’t find any documentation or reason for it other than that it may be a premature optimization.
I have observed the same issue with contact-form-7 a while back.
But note that registering shortcodes based on is_admin
is doing_it_wrong (see gmazzap`s answer)
There are the two reasons that seem legitimate at first sight (and why they are wrong):
-
(Unlikely) The plugin author tried to optimize the script to only register shortcodes when they are needed. In this case the author did not consider that the shortcode might be used in Ajax requests.
Wrong because: This optimization does not provide any performance gain. It simply adds a value to the global “registered shortcodes” array.
-
(This is the more likely one) The plugin author did intentionally disable the support for the shortcode in Ajax requests. With Contact-Form-7 this possibly is the case because forms can be set to “Submit via Ajax”. However, this feature requires the form to load additional javascript files which are not loaded when the shortcode is parsed via Ajax and javascript is added via enqueue_scripts()
.
The author decided to disable the Ajax support to prevent bug reports like “Don’t use this: Form is displayed but clicking the Submit button does not work. Complete waste of time!”
So the user will either see a guaranteed-working form or no form at all.
Wrong because: Checking for is_admin
is bad practice here. The conditon should check if the constant DOING_AJAX
is defined and true.
Though most plugins do not use this kind of condition, the few that have that restriction possibly have it because of problems in the past.
When a shortcode is simply doing some output on the page there is no reason to add any admin-condition. However, when the shortcode does also enqueue js or css files then it makes sense to limit the usage to non-admin/non-ajax requests.