I need a conditional which exits if the context is not a front-end view including AJAX requests. I have this at the moment:

if (is_admin() && !DOING_AJAX) 
    return;

The DOING_AJAX bit is required since is_admin() returns true for ajax requests. However I believe DOING_AJAX will be true for ALL ajax requests including those on the backend. Thus it doesn’t really add anything here.

How can I fork the two conditions? Can front-end/back-end ajax requests be distinguished?

thanks!

Clarification

Thanks for the insights but to clarify, in this instance, the hook itself is NOT an ajax action. It’s a filter hook into get_the_terms which needs to operate on any front-end request including any arbitrary theme or plugin ajax code. It also needs to bypass processing for the back-end hence the need for the forking condition. The problem is that ajax requests always return true for is_admin()

In case you are curious it’s a plugin which hides “secret” or “hidden” tags on the front-end, while still allowing their taxonomy pages to exist. The “hiding” needs to be bypassed on the backend for obvious reasons.

Thanks for the help. Sorry for the initial confusion!

5 Answers
5

DOING_AJAX and WP_ADMIN (this constant is checked within is_admin() ) are defined in admin-ajax.php and set tro true. Both are not very helpfull in this situation.

Add a parameter to your ajax request if the request come from the front-end:

<?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
}

In your ajax callback you can now check if the parameter is present and set to 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';
}

Leave a Reply

Your email address will not be published. Required fields are marked *