Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid menu_position conflicts when registering a page in WordPress admin?

Tags:

php

wordpress

In WordPress, when registering an admin page or a Custom Post Type, we can specify the menu_position. However, if two pages share the same menu_position then only one of them will be displayed.

How to avoid such conflicts in a multi-plugins/multi-devs environment such as WordPress? How can one check that a menu_position is not already taken?

Any value from 5 to 100 or even null can result in a conflict.

like image 749
Community Avatar asked Nov 01 '22 04:11

Community


1 Answers

Probably not the best solution but to minimise the risk try using decimals for positioning :) instead of "3" try using "3.1", "3.2", "3.3" etc...another way might be to use a function similar to:

function get_free_menu_position($start, $increment = 0.3)
{
    foreach ($GLOBALS['menu'] as $key => $menu) {
        $menus_positions[] = $key;
    }

    if (!in_array($start, $menus_positions)) return $start;

    /* the position is already reserved find the closet one */
    while (in_array($start, $menus_positions)) {
        $start += $increment;
    }
    return $start;
}

to give you the closest free position to the one you want....You can read more about it here

like image 134
Pavel Petrov Avatar answered Nov 08 '22 09:11

Pavel Petrov