Aquí hay un ejemplo;
Primero, para averiguar el orden de los elementos del submenú según su clave de matriz, puede hacer un var_dump
en la variable global $ submenu que dará como resultado lo siguiente:
(Estoy usando el menú de Entradas y el submenú como ejemplo)
//shortened for brevity....
["edit.php"]=>
array(6) {
[5]=>
array(3) {
[0]=> string(9) "All Posts"
[1]=> string(10) "edit_posts"
[2]=> string(8) "edit.php"
}
[10]=>
array(3) {
[0]=> string(7) "Add New"
[1]=> string(10) "edit_posts"
[2]=> string(12) "post-new.php"
}
[15]=>
array(3) {
[0]=> string(10) "Categories"
[1]=> string(17) "manage_categories"
[2]=> string(31) "edit-tags.php?taxonomy=category"
}
[17]=>
array(3) {
[0]=> string(14) "Sub Menu Title"
[1]=> string(10) "edit_posts"
[2]=> string(17) "sub_menu_page.php"
}
}
Podemos ver que mi elemento de submenú se agrega a la matriz con una clave de 17 después de los elementos predeterminados.
Si, por ejemplo, quiero agregar el elemento de mi submenú, inmediatamente después del elemento del submenú Todas las publicaciones , debo hacerlo configurando la clave de mi matriz en 6, 7, 8 o 9 ( cualquier cosa después de 5 y antes de 10 respectivamente.
Así es como lo haces ...
function change_submenu_order() {
global $menu;
global $submenu;
//set our new key
$new_key['edit.php'][6] = $submenu['edit.php'][17];
//unset the old key
unset($submenu['edit.php'][17]);
//get our new key back into the array
$submenu['edit.php'][6] = $new_key['edit.php'][6];
//sort the array - important! If you don't the key will be appended
//to the end of $submenu['edit.php'] array. We don't want that, we
//our keys to be in descending order
ksort($submenu['edit.php']);
}
Resultado,
["edit.php"]=>
array(6) {
[5]=>
array(3) {
[0]=> string(9) "All Posts"
[1]=> string(10) "edit_posts"
[2]=> string(8) "edit.php"
}
[6]=>
array(3) {
[0]=> string(14) "Sub Menu Title"
[1]=> string(10) "edit_posts"
[2]=> string(17) "sub_menu_page.php"
}
[10]=>
array(3) {
[0]=> string(7) "Add New"
[1]=> string(10) "edit_posts"
[2]=> string(12) "post-new.php"
}
[15]=>
array(3) {
[0]=> string(10) "Categories"
[1]=> string(17) "manage_categories"
[2]=> string(31) "edit-tags.php?taxonomy=category"
}
}
... pruébalo y dinos cómo te va.
Actualización 1:
Agregue esto a su archivo functions.php;
function change_post_menu_label() {
global $menu;
global $submenu;
$my_menu = 'example_page'; //set submenu page via its ID
$location = 1; //set the position (1 = first item etc)
$target_menu = 'edit.php'; //the menu we are adding our item to
/* ----- do not edit below this line ----- */
//check if our desired location is already used by another submenu item
//if TRUE add 1 to our value so menu items don't clash and override each other
$existing_key = array_keys( $submenu[$target_menu] );
if ($existing_key = $location)
$location = $location + 1;
$key = false;
foreach ( $submenu[$target_menu] as $index => $values ){
$key = array_search( $my_menu, $values );
if ( false !== $key ){
$key = $index;
break;
}
}
$new['edit.php'][$location] = $submenu[$target_menu][$key];
unset($submenu[$target_menu][$key]);
$submenu[$target_menu][$location] = $new[$target_menu][$location];
ksort($submenu[$target_menu]);
}
Mi actualización incluye una forma un poco más fácil de manejar la configuración de la posición del menú, solo tiene que estipular el nombre de la página del submenú y la posición que desea dentro del menú. Sin embargo, si selecciona una página de submenú $location
igual a la de una tecla existente, anulará esa tecla con la suya, por lo que el elemento de menú desaparecerá con su elemento de menú en su lugar. Incremente o disminuya el número para ordenar correctamente su menú si ese es el caso. De manera similar, si alguien instala un complemento que afecte esa misma área de menú, y para el cual tenga el mismo $location
que su elemento de submenú, se producirá el mismo problema. Para evitarlo, el ejemplo de Kaiser proporciona algunos ejemplos. Comprobación básica para eso.
Actualización 2:
Agregué un bloque de código adicional que verifica todas las claves existentes en el arreglo contra nuestro $location
deseado y si se encuentra una coincidencia, incrementaremos nuestro valor $location
en 1
para evitar elementos del menú anulando unos a otros. Este es el código responsable de eso,
//excerpted snippet only for example purposes (found in original code above)
$existing_key = array_keys( $submenu[$target_menu] );
if ($existing_key = $location)
$location = $location + 1;
Actualización 3: (secuencia de comandos revisada para permitir la clasificación de varios elementos del submenú)
add_action('admin_init', 'move_theme_options_label', 999);
function move_theme_options_label() {
global $menu;
global $submenu;
$target_menu = array(
'themes.php' => array(
array('id' => 'optionsframework', 'pos' => 2),
array('id' => 'bp-tpack-options', 'pos' => 4),
array('id' => 'multiple_sidebars', 'pos' => 3),
)
);
$key = false;
foreach ( $target_menu as $menus => $atts ){
foreach ($atts as $att){
foreach ($submenu[$menus] as $index => $value){
$current = $index;
if(array_search( $att['id'], $value)){
$key = $current;
}
while (array_key_exists($att['pos'], $submenu[$menus]))
$att['pos'] = $att['pos'] + 1;
if ( false !== $key ){
if (array_key_exists($key, $submenu[$menus])){
$new[$menus][$key] = $submenu[$menus][$key];
unset($submenu[$menus][$key]);
$submenu[$menus][$att['pos']] = $new[$menus][$key];
}
}
}
}
}
ksort($submenu[$menus]);
return $submenu;
}
En el ejemplo anterior, puede apuntar a varios submenús y múltiples elementos por submenú configurando los parámetros correspondientes dentro de la variable $target_menu
que contiene una matriz de valores multidimensional.
$target_menu = array(
//menu to target (e.g. appearance menu)
'themes.php' => array(
//id of menu item you want to target followed by the position you want in sub menu
array('id' => 'optionsframework', 'pos' => 2),
//id of menu item you want to target followed by the position you want in sub menu
array('id' => 'bp-tpack-options', 'pos' => 3),
//id of menu item you want to target followed by the position you want in sub menu
array('id' => 'multiple_sidebars', 'pos' => 4),
)
//etc....
);
Esta revisión evitará que los elementos del submenú se sobrescriban entre sí si tienen la misma clave (posición), ya que se desplazará hasta que encuentre una clave (posición) disponible que no existe.