Skip to content

Instantly share code, notes, and snippets.

@franz-josef-kaiser
Last active February 21, 2023 11:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save franz-josef-kaiser/1324722 to your computer and use it in GitHub Desktop.
Save franz-josef-kaiser/1324722 to your computer and use it in GitHub Desktop.
Add separators to WP Admin menus
<?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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment