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.