is_admin() and DOING_AJAX in Wordpress Plugins

2019-08-01 13:13发布

Im developing a Wordpress-plugin, where the main file of the plugins includes a PHP-file depending on (supposed to at least) if you are back-end or front-end.

As the is_admin() returns true on AJAX requests, I have used the DOING_AJAX constant to check whetever AJAX is done or not:

if ( is_admin() && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) ) {
    require_once('admin/functions_admin.php'); 
 }
 else { 
    require_once('public/functions_public.php'); 
 }

The correct file is loaded in wp-admin. The correct file is loaded front-end. Ajax-requests works front-end - but not back end. The "if" is not executed when doing Ajax back-end with this code.

When adding the following "else if" code it works back-end, but then not frond-end of course:

else if ( is_admin() ) {
   require_once('admin/functions_admin.php'); 
}

2条回答
一纸荒年 Trace。
2楼-- · 2019-08-01 13:48

Sorted this out by gathering all AJAX-functions (both front- and back-end) in a third file:

// Is admin, but not doing ajaax
if ( is_admin() && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) ) {
    require_once('admin/functions_admin.php'); 
}
// Is doing AJAX 
else if ( is_admin() && ( defined( 'DOING_AJAX' ) || DOING_AJAX ) ) {
    require_once('functions_ajax.php'); 
}
// Front-end functions
else { 
require_once('public/functions_public.php'); 
}
查看更多
孤傲高冷的网名
3楼-- · 2019-08-01 13:49

There is a note about this fact on the Ajax in plugin codex page.

As the hook use wp-admin/admin-ajax.php you must avoid using is_admin(), that will Always returns true.

An example, you want to include a file only on front end, you check with !is_admin(), in the file you have the wp_ajax_{$action} , but admin-ajax.php will Always return true, and the response will be 0.

What the codex says;

Both front-end and back-end Ajax requests use admin-ajax.php so is_admin() will always return true in your action handling code.

When selectively loading your Ajax script handlers for the front-end and back-end, and using the is_admin() function, your wp_ajax_(action) and wp_ajax_nopriv_(action) hooks MUST be inside the is_admin() === true part.

So, if your question is : how can i make my script works ?

Remove is_admin() and replace it with another conditional.

Source Ajax in plugin

Hope it helps

查看更多
登录 后发表回答