Как добавить разделитель в меню админки WordPress?
Не пойму как добавить разделитель в консоли.
Везде пишут про функцию add_admin_menu_separator(); но как я понимаю такой функции в wordpress просто нет.
Не пойму как добавить разделитель в консоли.
Везде пишут про функцию add_admin_menu_separator(); но как я понимаю такой функции в wordpress просто нет.
NOTE: Смотрите также пример по этой теме: https://wp-kama.ru/hook/admin_menu#example_38771
Да такой функции в WP нет, пишут про самописную функцию.
Посмотрел я в сети как она выглядит, недоделанная какая-то, может позволить себе удалить элемент меню, если неправильно указать индекс. В общем переделал как нужно.
/** * Добавляет разделитель в меню админки. * Проверяет наличие указанного интекса, если он есть увеличивает указанный индекс на 1. * Нужно это, чтобы не затереть существующие элементы меню, если указан одинаковый индекс. * * @param integer $position Индекс, в какое место добавлять разделитель * * @author kama * @ver 1.0 */ function add_admin_menu_separator( $position ){ global $menu; static $index; if( empty($index) ) $index = 1; foreach( $menu as $mindex => $section ){ if( $mindex >= $position ){ while( isset($menu[ $position ]) ) $position += 1; $menu[ $position ] = array( '', 'read', "separator-my$index", '', 'wp-menu-separator' ); $index++; break; } } ksort( $menu ); }Код работает с глобальной переменной напрямую, поэтому он не может быть стабильным, в будущих версиях ВП он когда-то может перестать работать.
Пример использования:
Этот код можно вставить в functions.php темы.
add_action( 'admin_menu', function(){ add_admin_menu_separator( 70 ); // дебаг посмотрим текущие индексы // die( print_r( $GLOBALS['menu'] ) ); } );Получим:
Cуть реализации
WordPress хранит разделы меню в глобальном массиве
$menu. Чтобы добавить разделитель, нужно добавить элемент в этот массив с индексом, который будет находиться между индексами других элементов, которые требуется разделить.Большое спасибо
Отличное решение. Позволил себе немного доработать его, что бы можно было вставлять разделитель не только по индексу, но и по имени елемента:
/** * Add a separator to the admin menu. * * @since 1.0.0 * @access public * @static * * @param string $target_item The menu item to add the separator, before or after. * @param bool $before Add the separator before the target item. Default is false. If false, the separator will be added after the target item. * * @return void **/ public static function add_admin_menu_separator( string $target_item, bool $before = false ): void { global $menu; $target_index = null; $max_numeric_key = 0; /** Find the target item and the maximum numeric key. */ foreach ( $menu as $key => $item ) { if ( is_numeric( $key ) && (int)$key > $max_numeric_key ) { $max_numeric_key = (int)$key; } if ( $item[0] === $target_item ) { $target_index = $key; break; } } /** Target item not found. */ if ( $target_index === null ) { return; } /** Determine the insertion index. */ $insert_index = $before ? $target_index : $target_index + 1; /** Find the first available numeric key. */ $new_index = $max_numeric_key + 1; while ( isset( $menu[$new_index] ) ) { $new_index++; } /** Create the new separator item. */ $new_separator = array( '', 'read', "wpk-separator-$new_index", '', 'wp-menu-separator' ); /** Shift the menu items. */ for ( $i = $new_index; $i > $insert_index; $i-- ) { if ( isset( $menu[$i - 1] ) ) { $menu[$i] = $menu[$i - 1]; } } /** Insert the new separator. */ $menu[$insert_index] = $new_separator; /** Sort the array by keys. */ ksort( $menu ); }Использовать как-то так:
/** Add menu separator after the "Bonuses" menu item. */ add_action( 'admin_menu', static function() { YourAwesomeClass::add_admin_menu_separator( 'Bonuses', true ); // Add separator before the "Bonuses" menu item. } );