I'm trying to early exit a function within the "init" hook if it's not a front-end page. This is what I have so far, but it's definitely running on wp-json endpoints. Does anyone have a complete "early exit" clause that will ensure this is ONLY running on front-end pages?

add_action('init', 'test'); 

function test() {

    if ( is_admin || wp_doing_ajax() ) {

    // Do stuff here

1 Answer 1


I wouldn't recommend detecting that it's not the admin or REST API, because with that approach you also need to detect that it's not a WP-Cron job, an AJAX request, or the login screen.

I think it's better to test for the front end directly, with wp_using_themes(). One caveat with that, is that you still need to make sure it's not a REST API request, for reasons.

if ( wp_using_themes() && ! _tmp_is_rest_api_request() ) {
    wp_die( 'i will only run on the front end' );

 * Returns true if the current request is for the REST API.
 * @todo: Replace this once Core provides a canonical way to do this: https://core.trac.wordpress.org/ticket/42061.
 * @return bool
function _tmp_is_rest_api_request() {
    if ( empty( $_SERVER['REQUEST_URI'] ) ) {
        return false;

    $rest_prefix = trailingslashit( rest_get_url_prefix() );

    return false !== strpos( $_SERVER['REQUEST_URI'], $rest_prefix );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.