Function and usage of get_plugin_page_hookname() in wordpress


Answers ( 1 )


    The get_plugin_page_hookname() function in WordPress is used to obtain the hook name for the administrative page of a plugin. This function is particularly useful when you're developing a plugin and need to work with WordPress' hook system to add custom functionality or modify existing behavior on plugin admin pages.

    Function Signature:

    get_plugin_page_hookname( string $plugin_page, string $parent_page ): string


    1. $plugin_page (string, required): The slug name of the plugin page. This is usually defined when you add a menu page for your plugin in the WordPress admin area using functions like add_menu_page() or add_submenu_page(). It's a unique identifier for your plugin's admin page.

    2. $parent_page (string, required): The slug name for the parent menu or the file name of a standard WordPress admin page. This parameter specifies under which parent menu the plugin page falls. For top-level menus, this could be a standard WordPress file name like 'admin.php', and for submenus, it's the slug of the parent menu.

    Return Value:

    • Return Type: string
    • Description: The function returns a string that is the hook name for the plugin page. This hook name can be used to target specific plugin pages for adding scripts, styles, or executing particular actions and filters.

    Sample Usage:

    Suppose you have a plugin with a settings page under the 'Settings' menu in WordPress. You want to enqueue a script specifically for this settings page.

    1. Defining the Plugin Page: In your plugin's main file, you might add a submenu page like this:

      add_action('admin_menu', 'my_plugin_add_settings_page');
      function my_plugin_add_settings_page() {
          add_submenu_page('options-general.php', 'My Plugin Settings', 'My Plugin', 'manage_options', 'my-plugin-settings', 'my_plugin_settings_page_callback');
    2. Using get_plugin_page_hookname(): To get the hook name for the plugin settings page, you'd do something like this:

      $hookname = get_plugin_page_hookname('my-plugin-settings', 'options-general.php');
    3. Using the Hook Name: Now, you can use this hook name to enqueue a script only on this specific settings page.

      add_action('admin_enqueue_scripts', 'my_plugin_enqueue_scripts');
      function my_plugin_enqueue_scripts($hook) {
          global $hookname;
          if ($hook != $hookname) return;
          wp_enqueue_script('my-plugin-script', plugins_url('script.js', __FILE__));

    In this example, the my_plugin_enqueue_scripts function checks if the current page's hook is the same as the one for our plugin's settings page. If it is, it enqueues a specific JavaScript file only on that page.

Leave an answer