I've added a custom link to WP Admin under the Users menu, but trouble is I can't seem to get it to display above the default options. Is this possible?

My code:

// Add sub-menu option to users menu to contractors section (shortcut)
add_action('admin_menu', 'my_add_contractors_submenu', 5);

function my_add_contractors_submenu() {
    global $submenu;
    $permalink = admin_url('users.php?role=contractor');
    $submenu['users.php'][] = array( 'Contractors', 'manage_options', $permalink );
}

Note that I used this method instead of add_submenu_page as I needed to add the link myself.

I've tried playing around with the priority parameter in the add_action but it won't go any higher - I'm trying to get it to display as the second option, just under " All Users".

有帮助吗?

解决方案

Take a look at this function.

function my_submenu_order($menu_ord) {
    global $submenu;

    // echo '<pre>'.print_r($submenu,true).'</pre>';

    $arr = array();
    $arr[] = $submenu['users.php'][15]; // Your Profile
    $arr[] = $submenu['users.php'][10]; // Add New
    $arr[] = $submenu['users.php'][5]; // All Users
    $submenu['users.php'] = $arr;

    return $menu_ord;
}

add_filter('custom_menu_order', 'my_submenu_order');

Add that to your functions.php. It changes the default order of the user's submenu from [5] [10] [15].

Now un-comment the echo and comment out everything else. This will output the menu item positions for everything. Look for your new submenu and add it to the list. So it would be something like this.

function my_submenu_order($menu_ord) {
    global $submenu;

    // echo '<pre>'.print_r($submenu,true).'</pre>';

    $arr = array();
    $arr[] = $submenu['users.php'][15];
    $arr[] = $submenu['users.php'][##]; // Add New Number
    $arr[] = $submenu['users.php'][10];
    $arr[] = $submenu['users.php'][5];
    $submenu['users.php'] = $arr;

    return $menu_ord;
}

add_filter('custom_menu_order', 'my_submenu_order');

EDIT

The above code works fine BUT if you were to add a plugin later that adds links to the Users submenu they wouldn't show up because we are wiping out the original menu and not including the new links (because we don't know what they are).

If that is a concern, instead of wiping out the menu we can add the newly sorted items to the end and remove the originals. See below.

function my_submenu_order($menu_ord) {
    global $submenu;

    // echo '<pre>'.print_r($submenu,true).'</pre>';

    // Build array of newly sorted items
    $arr = array();
    $arr[] = $submenu['users.php'][15]; // Your Profile
    $arr[] = $submenu['users.php'][10]; // Add New
    $arr[] = $submenu['users.php'][5]; // All Users

    // Remove the originals
    unset($submenu['users.php'][15]);
    unset($submenu['users.php'][10]);
    unset($submenu['users.php'][5]);

    // Add newly items to the list
    $submenu['users.php'] += $arr;

    return $menu_ord;
}

add_filter('custom_menu_order', 'my_submenu_order');
许可以下: CC-BY-SA归因
scroll top