函数文档

is_admin()

💡 云策文档标注

概述

is_admin() 函数用于判断当前请求是否针对 WordPress 管理界面页面。它不检查用户权限,仅基于请求上下文返回布尔值。

关键要点

  • 返回 true 表示在 WordPress 管理界面内,否则返回 false
  • 不验证用户角色或能力,需使用 current_user_can() 进行权限检查
  • 在主题定制器视图中返回 false,应使用 is_customize_preview() 检测
  • 在块编辑器环境中可能返回 false,需注意相关兼容性问题
  • 加载顺序较早,可在主题 functions.php 或插件中直接使用,无需等待主查询运行
  • 对于通过 wp-admin/admin-ajax.php 的 Ajax 请求返回 true,但自定义 Ajax 端点可能例外

代码示例

if ( ! is_admin() ) {
    // 仅在非管理界面(如主题模板)中运行
    echo 'Welcome to our website.';
} else {
    // 仅在管理界面(如插件文件)中运行
    echo 'Welcome to your Admin Panels.';
}

注意事项

  • 避免依赖 is_admin() 进行用户权限验证,应结合 current_user_can()
  • 在主题定制器或块编辑器等特殊上下文中,行为可能不符合预期,需使用专用函数检测
  • Ajax 请求的返回值取决于是否通过标准 admin-ajax.php 端点,自定义实现可能影响结果

📄 原文内容

Determines whether the current request is for an administrative interface page.

Description

Does not check if the user is an administrator; use current_user_can() for checking roles and capabilities.

For more information on this and similar theme functions, check out the Conditional Tags article in the Theme Developer Handbook.

Return

bool True if inside WordPress administration interface, false otherwise.

Source

function is_admin() {
	if ( isset( $GLOBALS['current_screen'] ) ) {
		return $GLOBALS['current_screen']->in_admin();
	} elseif ( defined( 'WP_ADMIN' ) ) {
		return WP_ADMIN;
	}

	return false;
}

Changelog

Version Description
1.5.1 Introduced.

User Contributed Notes

  1. Skip to note 8 content

    Example:

    if ( ! is_admin() ) {
        // Runs only if this PHP code is in a file that displays outside the admin panels, like the theme template.
        echo '<div style="text-align: center">Welcome to our website.</div>';
    } else {
        // Runs only if this code is in a file that displays inside the admin panels, like a plugin file.
        echo '<div style="text-align: center">Welcome to your Admin Panels.</div>';
    }

  2. Skip to note 11 content

    Note that is_admin() is available much earlier in the WordPress load sequence than other Conditional Tags and can be used before the main query has been run. This means it can be used in both the Theme functions.php file and in Plugins without needing to hook into an action or filter that triggers later.

  3. Skip to note 12 content

    is_admin() returns true for Ajax requests, since <a href="https://github.com/WordPress/WordPress/blob/master/wp-admin/admin-ajax.php" rel="nofollow ugc">wp-admin/admin-ajax.php</a> defines the WP_ADMIN constant as true.