How To Get Your WordPress Plugin’s Admin Page URL

blue and white round illustration

To get your plugin’s registered WordPress admin page URL with the page’s menu slug use the function menu_page_url(). However, this built-in WordPress function is bare-bones and doesn’t quite get the job done over the long run. A function that also allows you to add query parameters to the URL would be a lot more useful.

To create such a function, copy this code into your theme’s functions.php file – or plugin code if you’re making a custom plugin.

function get_admin_page_url(string $menu_slug, $query = null, array $esc_options = []) : string
{
    $url = menu_page_url($menu_slug, false);

    if($query) {
        $url .= '&' . (is_array($query) ? http_build_query($query) : (string) $query);
    }

    return esc_url($url, ...$esc_options);
}

Now, you can call the function.

For example, if you registered a menu page to the WordPress admin using add_menu_page() with the slug my_admin_page. You can use the following to get the URL for that admin page in the WordPress dashboard.

echo get_admin_page_url('my_admin_page');
// /wp-admin/admin.php?page=my_admin_page

Doing this is equivalent to calling menu_page_url() directly. However, the get_admin_page_url() function allows you to add URL query parameters too.

// You have two options
echo get_admin_page_url('my_admin_page', ['my_arg' => 1]);
echo get_admin_page_url('my_admin_page', 'my_arg=1');
// /wp-admin/admin.php?page=my_admin_page&my_arg=1

And, best of all, get_admin_page_url() works for pages registered with add_submenu_page() too.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.