函数文档

author_can()

💡 云策文档标注

概述

author_can() 函数用于检查指定文章的作者是否拥有给定的能力。它支持元能力检查,并可接受额外参数进行对象级验证。

关键要点

  • 函数返回布尔值,表示文章作者是否具备指定能力
  • 支持元能力(如 edit_post),通过 map_meta_cap() 映射到原始能力
  • 参数包括文章(ID 或 WP_Post 对象)、能力名称和可选参数(如对象 ID)
  • 内部使用 get_post() 和 get_userdata() 获取数据,调用 has_cap() 进行能力检查

代码示例

if ( author_can( $post->ID, 'publish_posts' ) ) {
    echo __( 'Yes they can publish posts!', 'textdomain' );
}

📄 原文内容

Returns whether the author of the supplied post has the specified capability.

Description

This function also accepts an ID of an object to check against if the capability is a meta capability. Meta capabilities such as edit_post and edit_user are capabilities used by the map_meta_cap() function to map to primitive capabilities that a user or role has, such as edit_posts and edit_others_posts.

Example usage:

author_can( $post, 'edit_posts' );
author_can( $post, 'edit_post', $post->ID );
author_can( $post, 'edit_post_meta', $post->ID, $meta_key );

Parameters

$postint|WP_Postrequired
Post ID or post object.
$capabilitystringrequired
Capability name.
$argsmixedoptional
Optional further parameters, typically starting with an object ID.

Return

bool Whether the post author has the given capability.

Source

function author_can( $post, $capability, ...$args ) {
	$post = get_post( $post );
	if ( ! $post ) {
		return false;
	}

	$author = get_userdata( $post->post_author );

	if ( ! $author ) {
		return false;
	}

	return $author->has_cap( $capability, ...$args );
}

Changelog

Version Description
5.3.0 Formalized the existing and already documented ...$args parameter by adding it to the function signature.
2.9.0 Introduced.

User Contributed Notes