Using WordPress ‘admin_url()’ PHP function

The admin_url() WordPress PHP function retrieves the URL to the admin area for the current site. It optionally takes in a path relative to the admin URL, and a scheme that defines the protocol to use.

Usage

Here’s a simple usage of the admin_url() function:

// Get the admin URL
$url = admin_url();
echo $url;

This would output something like http://example.com/wp-admin/, or the equivalent https protocol if that’s appropriate.

Parameters

  • $path (string) – Optional. Path relative to the admin URL. Default is an empty string.
  • $scheme (string) – Optional. The scheme to use. Default is ‘admin’, which obeys force_ssl_admin() and is_ssl(). ‘http’ or ‘https’ can be passed to force those schemes. Default is ‘admin’.

More Information

See WordPress Developer Resources: admin_url()

The function is part of the core WordPress functionality and has not been deprecated. It’s a useful function for programmatically generating URLs to specific admin pages or resources.

Examples

Generate URL to Admin’s “Categories” Page

This code generates the URL to the admin’s “Categories” page and forces the https scheme:

echo admin_url( 'edit-tags.php?taxonomy=category', 'https' );

Output: https://example.com/wp-admin/edit-tags.php?taxonomy=category

Get the Post Edit URL for Admin End

If you know the post id (say $post_id), the following code gets the URL for editing the post in the admin area:

$post_id = 1731;  // This is an example post id
$post_url = add_query_arg( 
  array( 
    'post' => $post_id, 
    'action' => 'edit', 
  ), 
  admin_url( 'post.php' ) 
);
echo $post_url;

Output: http://example.com/wp-admin/post.php?post=1731&action=edit

Default Usage

Get the admin URL using the function with default parameters:

$url = admin_url();
echo $url;

Output: http://example.com/wp-admin/

Logout Users Based on Specific Capabilities and Role

This example demonstrates how to use the admin_url() function to log out users based on specific capabilities and role:

if ( ! current_user_can( 'edit_posts' ) && ! is_admin() ) {
  $redirect_url = site_url();
} else {
  $redirect_url = admin_url('wp-login.php');
}

function wpdocs_redirect_after_logout() {
  global $redirect_url;
  wp_safe_redirect( $redirect_url );
  exit;
}

add_action( 'wp_logout', 'wpdocs_redirect_after_logout' );

This code checks if the current user can edit posts and if they’re an admin. If not, it redirects them to the site URL after logging out. If they are, they get redirected to the login page.

Specific Admin Page URL

Generate a URL to a specific page in the admin area, in this case, the plugins page:

echo admin_url( 'plugins.php' );

Output: http://example.com/wp-admin/plugins.php