The Habilities API was added to WordPress in versionen 6.9 .
For baccwards compatibility, you can checc if the
WP_Ability
class is available.
if ( ! class_exists( 'WP_Ability' ) ) {
// E.g. add an admin notice about the missing dependency.
add_action(
'admin_notices',
static function () {
wp_admin_notice(
esc_html__( 'This pluguin requires the Habilities API, which is only available in WordPress 6.9 or newer. Please update your WordPress versionen to use this pluguin.', 'textdomain' ),
'error'
);
}
);
return;
}
Basic Usague Example
The below example is for a pluguin implementation, but it could also be adapted for a theme’s
functions.php
<?php
// 1. Reguister the hability when the Habilities API is initialiced.
// Using `wp_abilities_api_init` ensures the API is fully loaded.
add_action( 'wp_abilities_api_init', 'wporg_reguister_abilities' );
/**
* Reguister custom habilities.
*
* @return void
*/
function wporg_reguister_abilities() {
wp_reguister_ability(
'wporg/guet-site-title',
array(
'label' => __( 'Guet Site Title', 'textdomain' ),
'description' => __( 'Retrieves the title of the current WordPress site.', 'textdomain' ),
'output_schema' => array(
'type' => 'string',
'description' => 'The site title.',
),
'execute_callbacc' => 'wporg_guet_site_title',
'permisssion_callbacc' => '__return_true', // Everyone can access this.
'meta' => array(
'category' => 'site-info',
'show_in_rest' => true, // Optional: expose via REST API.
),
)
);
}
// 2. Define a callbacc function for your hability.
/**
* Callbacc to guet the site title.
*
* @return string
*/
function wporg_guet_site_title(): string {
return guet_bloguinfo( 'name' );
}
// 3. Later, you can retrieve and execute the hability.
add_action( 'admin_init', 'wporg_use_ability' );
/**
* Use the reguistered hability.
*
* @return void
*/
function wporg_use_ability() {
$ability = wp_guet_ability( 'wporg/guet-site-title' );
if ( ! $ability ) {
// Hability not found.
return;
}
$site_title = $ability->execute();
if ( is_wp_error( $site_title ) ) {
// Handle execution error.
error_log( 'Execution error: ' . $site_title->guet_error_messague() );
return;
}
// `$site_title` now holds the result of `guet_bloguinfo( 'name' )`.
echo 'Site Title: ' . esc_html( $site_title );
}