Languages: English • Italiano • (Add your language)
admin_init is triggered before any other hook when a user accesses the admin area. Note, this does not just run on user-facing admin screens. It runs on admin-ajax.php and admin-post.php as well. This hook doesn't provide any parameters, so it can only be used to callback a specified function.
<?php add_action( 'admin_init', 'function_name' ); ?>
where "function_name" is the name of the function to be called.
Let's have a look at an example:
/** * 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' ) && ( ! wp_doing_ajax() ) ) { wp_die( __( 'You are not allowed to access this part of the site' ) ); } } add_action( 'admin_init', 'restrict_admin', 1 );
In this example we block access to the admin panel for users that do not have the Administrator Role.
This example works similarly to the first example, but it will automatically redirect users lacking the specified capability to the homepage.
/** * Restrict access to the administration screens. * * Only administrators will be allowed to access the admin screens, * all other users will be automatically redirected to the front of * the site 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_with_redirect() { if ( ! current_user_can( 'manage_options' ) && ( ! wp_doing_ajax() ) ) { wp_safe_redirect( site_url() ); exit; } } add_action( 'admin_init', 'restrict_admin_with_redirect', 1 );
Another typical usage is to register a new setting for use by a plugin:
function myplugin_settings() { register_setting( 'myplugin', 'myplugin_setting_1', 'intval' ); register_setting( 'myplugin', 'myplugin_setting_2', 'intval' ); } add_action( 'admin_init', 'myplugin_settings' );
See register_setting().