WordPress admin php page

How to Add WordPress Admin Pages

Sometimes a plugin or theme needs a new page in the admin area, this is post will explain how to do this.

There are a number of functions that can be called to make this happen, but they all use add_menu_page or add_submenu_page . Want to see how this all fits together? The code is on github.

The overview of this is that a function that calls add_menu_page , add_submenu_page , one of the other functions described below must be hooked into the admin_menu hook.

So in a normally bootstrapped WordPress plugin, that might look like this.

// hooked into `plugins_loaded` in the main plugin file function chrisguitarguy_adminpages_load() < add_action('admin_menu', 'chrisguitarguy_adminpages_add'); >function chrisguitarguy_adminpages_add() < // call `add_menu_page` or `add_submenu_page`, etc >

Adding a Top Level Menu Page

// hooked into `admin_menu`, see above function chrisguitarguy_adminpages_add() < add_menu_page( // page tag, localize it like any other user-facing string __('Example Top-Level Page', 'chrisguitarguy-adminpages'), // text displayed in the menu, localize it __('Example Top', 'chrisguitarguy-adminpages'), // what capability is required to access this? `manage_options` would be // an admin-level user. 'manage_options', // page url slug, prefix like anything else 'chrisguitarguy-adminpages-toplevel', // callback, this is called to display the actual page 'chrisguitarguy_adminpages_callback', // this is the icon URL, we'll skip this, but it can be used to // show a custom ICON in the menu. '', // position, where in the menu should this page be displayed? // higher number === lower on the page, can use ints or floats here 1000 ); > // show the page function chrisguitarguy_adminpages_callback() < include __DIR__.'/../views/page.php'; >

Here’s an illustration of where all those values passed end up displayed on the page.

Читайте также:  Python круги эйлера matplotlib

WordPress Admin add_menu_page

On the Admin Page $function

This callable is invoked by WordPress to actually show the page. I like to keep the actual HTML itself in a separate view file.

Whatever the organization, the callback should do two things to conform to the style of the rest of the WordPress admin.

  1. Wrap the entire admin page with a .
  2. Use an to show the page title.

Adding Submenu Pages

Call add_submenu_page instead of add_menu_page .

// hooked into `admin_menu`, see above function chrisguitarguy_adminpages_add() < add_submenu_page( // the page under which the submenu page should be nested 'options-general.php', // page tag, localize it like any other user-facing string __('Example Submenu Page', 'chrisguitarguy-adminpages'), // text displayed in the menu, localize it __('Example Submenu', 'chrisguitarguy-adminpages'), // what capability is required to access this? `manage_options` would be // an admin-level user. 'manage_options', // page url slug, prefix like anything else 'chrisguitarguy-adminpages-submenu', // callback, this is called to display the actual page 'chrisguitarguy_adminpages_callback' ); >

Here’s an illustration of where all those variables end up.

WordPress Admin add_submenu_page

There are quite a few other functions that are small wrappers around add_submenu_page that add pages under specific places in the admin area.

function chrisguitarguy_adminpages_add() < // Under Tools add_management_page( __('Example Management Page', 'chrisguitarguy-adminpages'), __('Example Manage', 'chrisguitarguy-adminpages'), 'manage_options', 'chrisguitarguy-adminpages-management', 'chrisguitarguy_adminpages_callback' ); // Under Settings add_options_page( __('Example Options Page', 'chrisguitarguy-adminpages'), __('Example Options', 'chrisguitarguy-adminpages'), 'manage_options', 'chrisguitarguy-adminpages-options', 'chrisguitarguy_adminpages_callback' ); // Under Appearance add_theme_page( __('Example Theme Page', 'chrisguitarguy-adminpages'), __('Example Theme', 'chrisguitarguy-adminpages'), 'manage_options', 'chrisguitarguy-adminpages-theme', 'chrisguitarguy_adminpages_callback' ); // Under Themes add_plugins_page( __('Example Plugin Page', 'chrisguitarguy-adminpages'), __('Example Plugin', 'chrisguitarguy-adminpages'), 'manage_options', 'chrisguitarguy-adminpages-plugin', 'chrisguitarguy_adminpages_callback' ); // Under Users add_users_page( __('Example User Page', 'chrisguitarguy-adminpages'), __('Example User', 'chrisguitarguy-adminpages'), 'manage_options', 'chrisguitarguy-adminpages-user', 'chrisguitarguy_adminpages_callback' ); >

WordPress Admin Submenu Pages

Adding Submenus Under Post Types

Submenu pages can be added under post types by using edit.php?post_type= as the $parent_slug argument.

To add a submenu page under the Pages area, for example:

function chrisguitarguy_adminpages_add() < // Under Pages add_submenu_page( 'edit.php?post_type=page', __('Example Post Type Page', 'chrisguitarguy-adminpages'), __('Example Type', 'chrisguitarguy-adminpages'), 'manage_options', 'chrisguitarguy-adminpages-type', 'chrisguitarguy_adminpages_callback' ); >

WordPress Admin Post Type Submenu

Permission Errors on Admin Pages

If any hook other than one of the admin_menu hooks is used to add the menu pages, a “Sorry, you are not allowed to access this page” message will be show.

Sorry You Are Not Allowed to Access This Page

function chrisguitarguy_adminpages_load() < add_action('admin_init', 'chrisguitarguy_adminpages_add'); >function chrisguitarguy_adminpages_add() < // . >

Always be sure to hook into admin_menu or one of the other hooks described below.

- add_action('admin_init', 'chrisguitarguy_adminpages_add'); + add_action('admin_menu', 'chrisguitarguy_adminpages_add');

Other Hooks for Adding Menu Pages

One of three hooks may be used to add menu page.

  1. admin_menu — what we’ve used here, this one always fires in single-site admin areas.
  2. network_admin_menu — fires in WordPress multi-site’s network admin area.
  3. user_admin_menu — fires in WordPress multi-site’s user admin area ( /wp-admin/user/ ).

Note that these hooks are exclusive. admin_menu will never fire on a network admin page, so choose the one that makes the most sense for the use case.

Источник

get_current_screen() │ WP 3.1.0

Получает объект данных о текущей странице админ-панели. С помощью этой функции можно, например, определить текущую страницу админки и использовать это в условии, чтобы, например, вывести что-либо на нужной странице админки. Или например, разделить работу скрипта для Страниц (page) и Записей (post) в админке.

current_screen — это самый ранний хук на котором можно использовать эту функцию. До этого хука данные о странице админки еще не собраны и функция вернет null.

Эта функция вернет null в AJAX запросе и вызовет Fatal Error на фронте (на фронте она не определена).

$current_screen (данные для этой функции) устанавливается поздно. После события init, когда уже начинает генерироваться HTML страницы админки. Определение переменной $current_screen происходит в файле wp-admin/admin.php функцией set_current_screen(). Файл admin.php подключается по всей админке.

Возвращает

WP_Screen|null . Объект данных WP_Screen или null, когда глобальная переменная $current_screen не установлена:

WP_Screen Object ( [id] => // Строка. Уникальный ID экрана. [action] => // Действие ассоциированное с экраном 'add' для *-new.php. Или пустой результат. [base] => post // Базовый тип экрана. Например, для страниц типа 'post-new.php' или 'post.php' базовый тип = 'post'. [parent_base] => edit // Базовый тип родительского пункта меню. Получается из $parent_file, удаляются параметры запроса и // '.php' расширение. Пр. 'edit.php?post_type=page' и 'edit.php?post_type=post' будут иметь родительскую базу 'edit' [parent_file] => edit.php // Родительский файл экрана из меню, пр.: 'edit.php?post_type=page', 'edit.php', 'options-general.php' [post_type] => post // Тип записи ассоциированный с экраном, если такой есть. Пр.:'edit.php?post_type=page' = 'page' [taxonomy] => // Таксономия ассоциированная с экраном, если есть. Пр.: 'edit-tags.php?taxonomy=category' = 'category' . (разные данные) )

Примеры

#1 Таблица id экранов админки в WordPress

Экран Файл $screen->id
Комментарии /wp-admin/edit-comments.php edit-comments
Темы /wp-admin/themes.php themes
Плагины /wp-admin/plugins.php plugins
Пост /wp-admin/post.php post
Пост (новый) /wp-admin/post-new.php post
Посты /wp-admin/edit.php edit-post
Страницы /wp-admin/edit.php edit-page
Тип записи /wp-admin/edit.php edit-
Термины /wp-admin/edit-tags.php edit-
Рубрики /wp-admin/edit-tags.php edit-category
Метки /wp-admin/edit-tags.php edit-post_tag
Медиа /wp-admin/upload.php upload
Юзеры /wp-admin/users.php users
МС Сайты /wp-admin/network/sites.php sites-network
МС Темы /wp-admin/network/themes.php themes-network
МС Юзеры /wp-admin/network/users.php users-network
МС Плагины /wp-admin/network/plugins.php plugins-network
MC Сайт: Темы /wp-admin/network/site-themes.php site-themes-network
MC Сайт: Юзеры /wp-admin/network/site-users.php site-users-network

#2 Запустим какой-либо код на странице Виджетов

add_action( 'current_screen', 'wpkama_widgets_screen' ); function wpkama_widgets_screen()< $screen = get_current_screen(); if( 'widgets' === $screen->id ) < // только на странице админки: Виджеты >>

#3 Добавим скрипт только на страницу редактирования записи

Этот пример показывает как добавить javascript код в подвал админ-панели, только на страницах редактирования/создания записей. Текст добавляется через фильтр admin_footer , в котором проверяется информация текущего экрана, если это страница редактирования записи, то выводится код:

id !== ‘post’ ) return; // // или можно так // if( get_current_screen()->parent_base !== ‘edit’ ) // return; ?>

WP_Screen Object ( [action] => add [base] => post [columns:WP_Screen:private] => 2 [id] => page [in_admin:protected] => site [is_network] => [is_user] => [parent_base] => edit [parent_file] => edit.php?post_type=page [post_type] => page [taxonomy] => [is_block_editor] => [_help_tabs:WP_Screen:private] => Array ( [about-pages] => Array ( [title] => О страницах [id] => about-pages [content] => 

Страницы похожи на записи тем, .

[callback] => ) [inserting-media] => Array ( [title] => Вставка медиа-файлов [id] => inserting-media [content] =>

Вы можете загружать и вставлять .

[callback] => ) [page-attributes] => Array ( [title] => Атрибуты страницы [id] => page-attributes [content] =>

Родительская — .

[callback] => ) ) [_help_sidebar:WP_Screen:private] =>

Дополнительная информация:

. [_options:WP_Screen:private] => Array ( [layout_columns] => Array ( [max] => 2 [default] => 2 ) ) [_show_screen_options:WP_Screen:private] => 1 [_screen_settings:WP_Screen:private] =>
. Растягивать редактор на высоту окна.
)

#4 Вкладка помощи

Этот пример показывает как создать контекстную помощь на созданной вами странице админки. Страница создается с помощью функции add_options_page(), add_menu_page() и им подобным. Допустим мы создали страницу с ярлыком ‘my_admin_page’, которая находится в пункте меню Настройки (options).

add_action( 'admin_menu', 'my_admin_add_page' ); function my_admin_add_page()< $page_hook = add_options_page( 'Страница настроек', 'Страница настроек', 'manage_options', 'my_opt_page_slug', 'my_admin_page'); // добавляем контекст при загрузке страницы add_action( "load-", 'my_admin_add_help_tab' ); > function my_admin_page() < echo 'Код страницы'; >function my_admin_add_help_tab()< $screen = get_current_screen(); // контент для вкладки помощь $screen->add_help_tab( array( 'id' => 'my_help_tab', 'title' => 'Помощь по странице', 'content' => '

Вспомогательное описание объясняющее непонятные места на странице

', ) ); >

Заметки

Список изменений

Код get_current_screen() get current screen WP 6.2.2

function get_current_screen() < global $current_screen; if ( ! isset( $current_screen ) ) < return null; >return $current_screen; >

Cвязанные функции

Админ-панель

  • add_menu_page()
  • add_meta_box()
  • add_options_page()
  • add_submenu_page()
  • add_theme_page()
  • do_meta_boxes()
  • get_admin_page_title()
  • get_admin_url()
  • includes_url()
  • is_admin()
  • remove_menu_page()
  • remove_meta_box()
  • remove_submenu_page()
  • wp_add_dashboard_widget()
  • wp_maintenance()

Источник

Оцените статью