0

I 've just noticed that the init event of a plugin I write myself keeps firing every minute or so if any dashboard's page is loaded in the browser, without interacting with it or even focus on it.

Is this behavior expected? I cant find any information about it, am I missing something ?

3
  • The init event is fired every time WordPress is initialized, both front end and backend (wp-admin). What do you mean with "dashboard's page" and with "without interacting with it or even focus on it"?
    – cybmeta
    Mar 25, 2015 at 10:17
  • I don't know if I can be more explanatory, but I' ll try. If I leave any admin/backend page loaded on a browser's tab, the init event keeps firing even if the tab is not active/focused. Of course no other page of the specific WP installation is opened neither backend nor frontend. Mar 25, 2015 at 10:43
  • 1
    Your dashboard regularly makes Ajax requests, that's triggering the init most probably. Have a look at the network tab.
    – RRikesh
    Mar 25, 2015 at 11:05

1 Answer 1

6

This happens because you are not excluding ajax requests.

Check this example from the WordPress Codex for the admin_init hook which is also valid for the init hook and see how AJAX requests are exluded in the if using the DOING_AJAX constant:

/**
 * Restrict access to the administration screens.
 *
 * Only administrators will be allowed to access the admin screens,
 * all other users will be shown a message instead.
 *
 * We do allow access for Ajax requests though, since these may be
 * initiated from the front end of the site by non-admin users.
 */
function restrict_admin() {

    if ( ! current_user_can( 'manage_options' ) && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) ) {
        wp_die( __( 'You are not allowed to access this part of the site' ) );
    }
}
add_action( 'admin_init', 'restrict_admin', 1 );

You can use this as a starting point:

add_action( 'init', 'wpse_182220_init' );
function wpse_182220_init() {

    // Exit function if doing an AJAX request
    if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
        return;
    }

    echo 'OK, not doing AJAX';

}

Props to RRikesh for mentioning it in his comment.

1
  • very nice solution - I've been looking for that few hours ;) Dec 7, 2020 at 11:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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