public

Add separators to WP Admin menus

  • Download Gist
insert_menu_separator.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
<?php
 
namespace WCM;
 
// Add the filter
add_action( 'admin_menu', __NAMESPACE__.'\add_menu_separator' );
function add_menu_separator()
{
add_filter( 'add_menu_classes', __NAMESPACE__.'\insert_admin_menu_separator' );
}
 
/**
* Adds separators for menu item groups
*
* @param (array) $menu
*/
function insert_admin_menu_separator( $menu )
{
// Targeted elements
$targets = array(
'Books'
);
 
// Need the keys as numeric array for easier look up
$index = array_keys( $menu );
 
foreach ( $targets as $target )
{
foreach ( $menu as $m_pos => $m )
{
foreach ( $m as $key => $data )
{
// Get index from keys array - strict to speed things up
if ( $target === $data )
$pos_first = array_search( $m_pos, $index, true );
}
}
// Get menu position from current, previous & next element
$prev_el = $index[ $pos_first - 1 ];
$next_el = $index[ $pos_first + 1 ];
$curr_el = $index[ $pos_first ];
 
// Check if (exactly) previous key has no separator attached
// and is not set (else we'd overwrite the element)
if ( ! isset( $menu[ $curr_el - 1 ] ) AND $menu[ $curr_el - 1 ] !== 'wp-menu-separator' )
{
$separator = array(
0 => '',
1 => 'read',
2 => 'separator',
3 => '',
4 => 'wp-menu-separator',
);
// insert separator before the targeted element (first in group)
$menu[ $curr_el - 1 ] = $separator;
}
elseif ( isset( $menu[ $curr_el - 1 ] ) )
{
# @todo Move index around
}
 
// Add css classes to previous element
$prev = $menu[ $prev_el ][4];
$menu[ $prev_el ][4] = add_cssclass( 'menu-top-last', $prev );
 
// Add css classes to next element
$next = $menu[ $next_el ][4];
$menu[ $next_el ][4] = add_cssclass( 'menu-top-first', $next );
}
 
// sort
uksort( $menu, 'strnatcasecmp' );
 
return $menu;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.