Paulund
2015-01-19 #wordpress

Taxonomy Page Parent Menu Collapsed

WordPress allows you to create your own menus in the admin area, to do this you can use the function add_menu_page().


<?php
add_menu_page( $page_title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position );
?>

When this menu item is in place you are also able to add sub-menu items to the page that can be used to make your own custom option pages under this menu by using the function add_submenu_page().


<?php add_submenu_page( $parent_slug, $page_title, $menu_title, $capability, $menu_slug, $function ); ?>

Using the submenu page you can add any URL you want to the menu items anything from a settings page, link to the front-end, link to a custom post types, link to custom taxonomy. If you were to add a custom taxonomy edit tags page /wp-admin/edit-tags.php?taxonomy=category to the menu you will see different behaviour with the menus then with other submenu pages. When you add a sub-menu page WordPress will automatically expand the parent menu item to visually show where in the hierarchy you currently are. But with a custom taxonomy page WordPress will not understand it's parent item in the menu and will collapse the menu item. Using the below snippet you can add a new Javascript file to the page to check to see if the top level menu item is open on a certain page, if it's not then we add the CSS class to expand the menu item.


add_action('admin_head', 'pu_set_open_menu');

/**
 * Open the correct menu for taxonomy
 */
public function pu_set_open_menu()
{
    $screen = get_current_screen();
    if( $screen->base === 'edit-tags' && $screen->taxonomy === 'taxonomy_type_name' )
    {
        wp_enqueue_script( 'open-menu-parent', plugins_url('../assets/js/admin-menu.js', __FILE__ ), array('jquery') );
    }
}

As you can see from the code above we can discover what page we are on by using the get_current_screen() function, this allows us to get the base page and check the taxonomy type to make sure we're on the right page before adding the Javascript file.


(function ( $ ) {
    // Close all the other parent menus
    $('.wp-has-current-submenu').removeClass('wp-has-current-submenu');

    // Open your specific parent menu
    $('.toplevel_page_top-menu-level-item')
        .removeClass('wp-not-current-submenu')
        .addClass('wp-has-current-submenu wp-menu-open');

}(jQuery));