函数文档

admin_url()

💡 云策文档标注

概述

admin_url() 函数用于获取当前站点的管理区域 URL,支持附加路径和指定协议方案。它是 WordPress 核心函数,常用于生成后台链接。

关键要点

  • 函数返回当前站点的管理区域 URL,默认基于 force_ssl_admin() 和 is_ssl() 确定协议。
  • 参数 $path 可选,用于附加相对路径到管理 URL,如 'edit-tags.php?taxonomy=category'。
  • 参数 $scheme 可选,可指定 'admin'(默认)、'http' 或 'https' 来强制协议。
  • 函数内部调用 get_admin_url(),简化了获取管理 URL 的过程。
  • 在 WordPress 2.6.0 版本中引入,广泛用于插件和主题开发中生成后台链接。

代码示例

// 基本用法:获取管理区域 URL
echo admin_url(); // 输出如 http://example.com/wp-admin/

// 附加路径并强制 HTTPS
echo admin_url('edit-tags.php?taxonomy=category', 'https'); // 输出如 https://example.com/wp-admin/edit-tags.php?taxonomy=category

// 路径中的前导斜杠会被自动移除,不影响输出
admin_url('test');  // 返回 http://example.com/wp-admin/test
admin_url('/test'); // 同样返回 http://example.com/wp-admin/test

注意事项

  • 使用 $scheme 参数时,'admin' 值会根据站点 SSL 设置自动选择协议,而 'http' 或 'https' 会强制使用指定协议。
  • 路径参数 $path 应使用相对路径,避免包含域名,以确保 URL 正确构建。
  • 该函数常用于生成后台页面链接,如编辑文章或分类页面,结合 add_query_arg() 可进一步定制查询参数。

📄 原文内容

Retrieves the URL to the admin area for the current site.

Parameters

$pathstringoptional
Path relative to the admin URL. Default empty.
$schemestringoptional
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.

Return

string Admin URL link with optional path appended.

Source

function admin_url( $path = '', $scheme = 'admin' ) {
	return get_admin_url( null, $path, $scheme );
}

Changelog

Version Description
2.6.0 Introduced.

User Contributed Notes

  1. Skip to note 8 content

    If you are looking for the post edit url for admin end and you have the post id (suppose $post_id) with you, then you can use the following code for getting the url.

    $post_id = 1731; // For example
    $post_url = add_query_arg( array( 
    	'post' => $post_id, 
    	'action' => 'edit', 
    ), admin_url( 'post.php' ) );
    
    // returns <a href="http://example.com/wp-admin/post.php?post=1731&action=edit" rel="nofollow ugc">http://example.com/wp-admin/post.php?post=1731&action;=edit</a>

  2. Skip to note 10 content

    The presence of a leading slash in the path doesn’t affect the output, as it will be internally removed. Thus, both calls to admin_url() will yield the same result:

    admin_url( 'test' );  // returns <a href="http://example.com/wp-admin/test" rel="nofollow ugc">http://example.com/wp-admin/test</a>
    admin_url( '/test' ); // returns <a href="http://example.com/wp-admin/test" rel="nofollow ugc">http://example.com/wp-admin/test</a>

  3. Skip to note 11 content

    Logout Users based on specific capabilities and role

    if ( ! current_user_can( 'edit_posts' ) && ! is_admin() ) {
    	$redirect_url = site_url();
    } else {
    	$redirect_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' );