WordPress.org

Ready to get started?Download WordPress

Codex

Attention Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Plugin API/Action Reference/admin init

Description

admin_init is triggered before any other hook when a user accesses the admin area. This hook doesn't provide any parameters, so it can only be used to callback a specified function.

Usage

<?php add_action( 'admin_init', 'function_name' ); ?>

where "function_name" is the name of the function to be called.

Example: Access control

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' ) && ( ! 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 );

In this example we block access to the admin panel for users that do not have the Administrator Role.

Example: Access Control with redirect

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' ) && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) ) {
		wp_redirect( site_url() ); 
		exit;
	}
}

add_action( 'admin_init', 'restrict_admin_with_redirect', 1 );

Example: Registering new settings

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().