函数文档

wp_ensure_editable_role()

💡 云策文档标注

概述

wp_ensure_editable_role() 是一个 WordPress 函数,用于检查当前用户是否有权限分配指定角色,若无权限则终止执行并显示错误信息。

关键要点

  • 函数接受一个必需参数 $role,表示用户尝试分配的角色字符串。
  • 通过 get_editable_roles() 获取当前用户可编辑的角色列表,检查 $role 是否在其中。
  • 如果 $role 不在可编辑角色列表中,调用 wp_die() 终止执行,显示 403 错误消息。
  • 此函数在 WordPress 6.8.0 版本中引入。

代码示例

function wp_ensure_editable_role( $role ) {
	$roles = get_editable_roles();
	if ( ! isset( $roles[ $role ] ) ) {
		wp_die( __( 'Sorry, you are not allowed to give users that role.' ), 403 );
	}
}

注意事项

  • 函数主要用于权限验证,确保用户角色分配操作的安全性。
  • 相关函数包括 get_editable_roles()、__() 和 wp_die(),用于获取角色列表、翻译文本和错误处理。

📄 原文内容

Stop execution if the role can not be assigned by the current user.

Parameters

$rolestringrequired
Role the user is attempting to assign.

Source

function wp_ensure_editable_role( $role ) {
	$roles = get_editable_roles();
	if ( ! isset( $roles[ $role ] ) ) {
		wp_die( __( 'Sorry, you are not allowed to give users that role.' ), 403 );
	}
}

Changelog

Version Description
6.8.0 Introduced.