Plugin API/Action Reference/admin init

跳转至: 导航搜索


admin_init is triggered before any other hook when a user access the admin area. 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.

Example: Access control

Let's have a look at an example:

function restrict_admin(){
	//if not administrator, kill WordPress execution and provide a message
	if ( ! current_user_can( 'manage_options' ) ) {
		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.

function restrict_admin_with_redirect() {
	if ( ! current_user_can( 'manage_options' ) && $_SERVER['PHP_SELF'] != '/wp-admin/admin-ajax.php' ) {
		wp_redirect( site_url() ); exit;

add_action( 'admin_init', 'restrict_admin_with_redirect' );

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' );