Had a situation today where I was using admin-ajax.php from a front end script. As I understand it this the wp way to make ajax calls (registering my function with the wp_ajax_nopriv_myfunction hook)
Seems to me that since admin-ajax.php is on the admin side is_admin() returns true whereas my script calls it from the front end side.
This causes an issue with a plugin I use that does things differently on front and admin side of things.
So I was wondering if I was doing something wrong
is there a way to use ajax in front end the wp way and have is_admin() to return false ?
hope I could make myself understand
WordPress sets
is_admin()
to true for all ajax requests (front-end or admin-side). (See codex).There’s isn’t away of over-riding this (and you shouldn’t anyway). If your ajax request can be fired from both front-end and admin side, then you may want to include whether it ‘is admin’ or not when you post the data. But without any details on the ‘issues’ it causes with your plug-in, it’s hard to offer a work-aroudn.
is_admin()
always returnstrue
for every AJAX call. If you want to validate AJAX calls from frontend only, this may be a work-around:I know this is old, but in case it helps anybody else that stumbles across this…
what I usually do is set some kind of flag in my frontend forms to denote that the incoming request is ajax.
Initially this is set to “false”, which i then toggle to “true” while beginning to process the ajax.
then in the admin side of my code, i check for that parameter and then either include my ajax hooks or perform my regular non-ajax admin stuff. So for example:
depending on what you need to do, there are multiple variations of this idea, but it allows you to keep your regular admin code from interfering or firing while performing ajax requests.
another recommendation that can be handy is setting the WordPress “noheader” attribute in your forms.
when doing backend processing that ultimately results in a redirect (recommended for avoiding the dreaded double form submission), in rare fringe cases where you need to access wp hooks that would normally occur after “headers already sent”.
I wanted to enable/disable logging on the front end and admin using a dashboard menu button. I simply added a class to my menu button and then queried admin page status with jQuery
https://codex.wordpress.org/Class_Reference/WP_Admin_Bar/add_menu
Add a menu item with the admin status as a class
Get the menu item using jQuery in javascript and use it:
@fuxia’s comment is the best if you want to test and specifically include ajax calls:
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) :
and @wpclevel’s answer is best if you want to test to specifically exclude any admin/dashboard screens:
if ( ! isset( $GLOBALS['current_screen'] ) && ! is_customize_preview() ) :
There is a lot of overlapping use cases where either one would work, but sometimes you will need one or the other of these solutions.