DOING_AJAX
和WP_ADMIN
(该常数在is_admin()
) 在管理ajax中定义。php并将tro设置为true。在这种情况下,两者都没有多大帮助。
如果请求来自前端,请在ajax请求中添加一个参数:
<?php
function my_action_javascript() {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
var data = {
action: \'my_action\',
frontend_request: true,
whatever: 1234
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
$.post(ajaxurl, data, function(response) {
alert(\'Got this from the server: \' + response);
});
});
</script>
<?php
}
在ajax回调中,现在可以检查参数是否存在并设置为true:
$from_frontend = isset( $_REQUEST[\'frontend_request\'] ) && ( TRUE === (bool) $_REQUEST[\'frontend_request\'] );
$doing_ajax = defined( \'DOING_AJAX\' ) && TRUE === DOING_AJAX;
$is_frontend_request = $frontend && $doing_ajax;
if( TRUE === $is_frontend_request ){
// yes, this request came from the front-end
echo \'On frontend\';
} else {
// no, we are somewhere else
echo \'Somewhere else\';
}