函数文档

wp_has_ability()

💡 云策文档标注

概述

wp_has_ability() 函数用于检查指定的能力是否已在 WordPress 中注册,适用于条件逻辑和功能检测场景。

关键要点

  • 函数接受一个字符串参数 $name,表示要检查的能力名称(需包含命名空间前缀,如 'my-plugin/my-ability')。
  • 返回布尔值:true 表示能力已注册,false 表示未注册。
  • 内部通过 WP_Abilities_Registry::get_instance() 获取注册表实例,并调用 is_registered() 方法进行验证。

代码示例

// Displays different UI based on available abilities.
if ( wp_has_ability( 'premium-plugin/advanced-export' ) ) {
    echo 'Export with Premium Features';
} else {
    echo 'Basic Export';
}

注意事项

  • 在尝试检索或使用能力前,建议先调用此函数进行检测,以避免潜在错误。
  • 相关函数包括 WP_Abilities_Registry::is_registered() 和 wp_get_ability(),可用于进一步操作。
  • 此函数自 WordPress 6.9.0 版本引入。

📄 原文内容

Checks if an ability is registered.

Description

Use this for conditional logic and feature detection before attempting to retrieve or use an ability.

Example:

// Displays different UI based on available abilities.
if ( wp_has_ability( 'premium-plugin/advanced-export' ) ) {
    echo 'Export with Premium Features';
} else {
    echo 'Basic Export';
}

See also

Parameters

$namestringrequired
The name of the ability to check, including namespace prefix (e.g., 'my-plugin/my-ability').

Return

bool true if the ability is registered, false otherwise.

Source

function wp_has_ability( string $name ): bool {
	$registry = WP_Abilities_Registry::get_instance();
	if ( null === $registry ) {
		return false;
	}

	return $registry->is_registered( $name );
}

Changelog

Version Description
6.9.0 Introduced.