钩子文档

admin_head-{$hook_suffix}

💡 云策文档标注

概述

admin_head-{$hook_suffix} 是一个 WordPress 动作钩子,用于在特定管理页面的头部区域触发自定义代码。开发者可以利用此钩子向页面输出内容或执行后台任务。

关键要点

  • 这是一个动态钩子,$hook_suffix 参数对应管理页面的钩子后缀,用于指定目标页面。
  • 钩子不提供参数,函数应通过 echo 输出内容或执行任务,不应返回值或接受参数。
  • 常用于工具页面或选项页面,通过 add_action 绑定到特定管理页面。

代码示例

// 工具页面示例
add_action('admin_head-tools_page_myplugin/myplugin', 'myplugin_adminhead');
function myplugin_adminhead() {
    // 输出内容,例如:
    echo '<style>/* 自定义样式 */</style>';
}

// 选项页面示例
add_action( 'admin_menu', 'myplugin_setup_options' );
function myplugin_setup_options(){
  $plugin_page = add_options_page( 'My Plugin', 'myplugin', 8, basename(__FILE__), 'myplugin_main' );
  add_action( 'admin_head-'. $plugin_page, 'myplugin_admin_header' );
}
function myplugin_admin_header(){
  echo 'Only executes when the myplugin options page is displayed.';
}

注意事项

  • 此钩子是一个动作钩子,主要用于触发事件,而非过滤内容,使用时需注意其语义。
  • 确保 $hook_suffix 正确匹配目标管理页面,以避免钩子不触发。

📄 原文内容

Fires in head section for a specific admin page.

Description

The dynamic portion of the hook name, $hook_suffix, refers to the hook suffix for the admin page.

More Information

This hook provides no parameters. You use this hook by having your function echo output to the browser, or by having it perform background tasks. Your functions shouldn’t return, and shouldn’t take any parameters.

Source

do_action( "admin_head-{$hook_suffix}" ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores

Changelog

Version Description
2.1.0 Introduced.

User Contributed Notes

  1. Skip to note 3 content

    (From Codex)
    Tools pages

    To add content to a management page, the suffix for this hook should be in the following form:

    add_action('admin_head-tools_page_myplugin/myplugin', 'myplugin_adminhead');
    function myplugin_adminhead() {
        // Output <head> content here, e.g.:
        echo '<style type="text/css">'
             .'/* ... */'
             .'</style>';
    }

  2. Skip to note 4 content

    (From Codex)
    Options pages

    This hook is an action which means that it primarily acts as an event trigger, instead of a content filter. This is a semantic difference, but it will help you to remember what this hook does if you use it like this:

    add_action( 'admin_menu', 'myplugin_setup_options' );
    
    function myplugin_setup_options(){
      $plugin_page=add_options_page( 'My Plugin', 'myplugin', 8, basename(__FILE__), 'myplugin_main' );
      add_action( 'admin_head-'. $plugin_page, 'myplugin_admin_header' );
    }
    
    function myplugin_admin_header(){
      echo '<p>Only executes when the myplugin options page is displayed.</p>';
    }