### Install Development Dependencies Source: https://github.com/wordpress/abilities-api/blob/trunk/CONTRIBUTING.md Install Node.js and NPM dependencies. If using Composer locally, also install PHP dependencies. ```bash ## If you're using nvm, make sure to use the correct Node.js version: nvm install && nvm use ## Then install the NPM dependencies: npm install # If you are using Composer locally, also run: composer install ``` -------------------------------- ### Start Local Development Environment Source: https://github.com/wordpress/abilities-api/blob/trunk/CONTRIBUTING.md Start the local development environment using wp-env. Access the site at http://localhost:8888. ```bash npm run wp-env start ``` -------------------------------- ### Install JavaScript Dependencies Source: https://github.com/wordpress/abilities-api/blob/trunk/CONTRIBUTING.md Install JavaScript dependencies using NPM. This is a standard step after cloning the repository. ```bash npm install ``` -------------------------------- ### Install Abilities API with Composer Source: https://github.com/wordpress/abilities-api/blob/trunk/docs/getting-started.md Add the Abilities API as a Composer dependency to your project. ```bash composer require wordpress/abilities-api ``` -------------------------------- ### Install Abilities API via Composer or WP-CLI Source: https://context7.com/wordpress/abilities-api/llms.txt Provides commands for installing the Abilities API as a Composer dependency or a WordPress plugin. ```bash # As a Composer dependency composer require wordpress/abilities-api # As a plugin via WP-CLI wp plugin install https://github.com/WordPress/abilities-api/releases/latest/download/abilities-api.zip --activate ``` -------------------------------- ### Install Abilities API with WP-CLI Source: https://github.com/wordpress/abilities-api/blob/trunk/docs/getting-started.md Use WP-CLI to install the Abilities API plugin from a remote URL. ```bash wp plugin install https://github.com/WordPress/abilities-api/releases/latest/download/abilities-api.zip ``` -------------------------------- ### Register and Use an Ability Source: https://github.com/wordpress/abilities-api/blob/trunk/docs/getting-started.md Example demonstrating how to define a callback, register an ability using 'wp_register_ability', and then retrieve and execute it using 'wp_get_ability'. ```php __( 'Get Site Title', 'my-plugin' ), 'description' => __( 'Retrieves the title of the current WordPress site.', 'my-plugin' ), 'category' => 'site-info', 'input_schema' => array( 'type' => 'object', 'properties' => array(), 'additionalProperties' => false, ), 'output_schema' => array( 'type' => 'string', 'description' => 'The site title.', ), 'execute_callback' => 'my_plugin_get_site_title', 'permission_callback' => '__return_true', // Everyone can access this 'meta' => array( 'show_in_rest' => true, // Optional: expose via REST API ), ) ); } // 3. Later, you can retrieve and execute the ability. add_action( 'admin_init', 'my_plugin_use_ability' ); function my_plugin_use_ability() { $ability = wp_get_ability( 'my-plugin/get-site-title' ); if ( ! $ability ) { // Ability not found. return; } $site_title = $ability->execute(); if ( is_wp_error( $site_title ) ) { // Handle execution error error_log( 'Execution error: ' . $site_title->get_error_message() ); return; } // `$site_title` now holds the result of `get_bloginfo( 'name' )`. echo 'Site Title: ' . esc_html( $site_title ); } ``` -------------------------------- ### Clone the Abilities API Repository Source: https://github.com/wordpress/abilities-api/blob/trunk/CONTRIBUTING.md Clone the repository to your local machine to begin development. Ensure you have Git installed. ```bash git clone https://github.com/WordPress/abilities-api.git ``` -------------------------------- ### Install PHP Dependencies Source: https://github.com/wordpress/abilities-api/blob/trunk/CONTRIBUTING.md Install PHP dependencies using Composer. This is typically done after cloning the repository or when updating dependencies. ```bash composer install ``` -------------------------------- ### Registering an Ability Source: https://github.com/wordpress/abilities-api/blob/trunk/docs/php-api.md This example demonstrates how to register a new ability using the `wp_register_ability()` function, specifying all required parameters and optional metadata. ```APIDOC ## wp_register_ability() ### Description Registers a new ability with the WordPress system. Abilities represent discrete actions or operations that can be performed. ### Parameters `$name` (string, Required): The unique name for the ability, following the `namespace/ability-name` convention. `$args` (array, Required): An array of arguments defining the ability's properties. #### `$args` Keys: - `label` (string, **Required**): A human-readable name for the ability. Should be translatable. - `description` (string, **Required**): A detailed description of the ability's purpose and usage. Should be translatable. - `category` (string, **Required**): The slug of the category the ability belongs to. Must be pre-registered. - `input_schema` (array, Optional): A JSON Schema defining the expected input parameters. - `output_schema` (array, **Required**): A JSON Schema defining the expected output format. - `execute_callback` (callable, **Required**): The PHP callback function to execute when the ability is invoked. - `permission_callback` (callable, **Required**): A callback function to check user permissions for executing the ability. - `meta` (array, Optional): An associative array for additional metadata. - `annotations` (array, Optional): Hints about the ability's behavior. - `instructions` (string, Optional): Custom instructions for using the ability. - `readonly` (boolean, Optional): Whether the ability only reads data. - `destructive` (boolean, Optional): Whether the ability performs destructive updates. - `idempotent` (boolean, Optional): Whether repeated calls have no additional effect. - `show_in_rest` (boolean, Optional): Whether to expose the ability via the REST API. - `ability_class` (string, Optional): The fully-qualified class name of a custom ability class extending `WP_Ability`. ### Ability Name Convention - **Format:** `namespace/ability-name` (lowercase alphanumeric, hyphens, one slash). - **Convention:** Use plugin slug as namespace (e.g., `my-plugin/ability-name`). ### Example ```php wp_register_ability( 'my-plugin/process-data', [ 'label' => __( 'Process Data', 'my-plugin' ), 'description' => __( 'Processes the provided data and returns a summary.', 'my-plugin' ), 'category' => 'data-processing', 'input_schema' => [ 'type' => 'object', 'properties' => [ 'data' => ['type' => 'array', 'items' => ['type' => 'string']], ], 'required' => ['data'], ], 'output_schema' => [ 'type' => 'object', 'properties' => [ 'summary' => ['type' => 'string'], 'processed_count' => ['type' => 'integer'], ], ], 'execute_callback' => function( $input ) { // Implementation to process data $count = count( $input['data'] ); return ['summary' => 'Processed ' . $count . ' items.', 'processed_count' => $count]; }, 'permission_callback' => function() { return current_user_can( 'manage_options' ); }, 'meta' => [ 'annotations' => [ 'instructions' => 'Provide an array of strings to process.', 'readonly' => false, 'destructive' => false, 'idempotent' => false, ], 'show_in_rest' => true, ], 'ability_class' => 'MyPlugin\Abilities\ProcessDataAbility', ] ); ``` ``` -------------------------------- ### List Categories Request Source: https://github.com/wordpress/abilities-api/blob/trunk/docs/rest-api.md Example cURL request to list all ability categories. Requires authentication with username and application password. ```bash curl -u 'USERNAME:APPLICATION_PASSWORD' \ https://example.com/wp-json/wp-abilities/v1/categories ``` -------------------------------- ### List Abilities Response Source: https://github.com/wordpress/abilities-api/blob/trunk/docs/rest-api.md Example JSON response when listing abilities. Each ability object details its name, label, description, category, output schema, and meta. ```json [ { "name": "my-plugin/get-site-info", "label": "Get Site Information", "description": "Retrieves basic information about the WordPress site.", "category": "site-information", "output_schema": { "type": "object", "properties": { "name": { "type": "string", "description": "Site name" }, "url": { "type": "string", "format": "uri", "description": "Site URL" } } }, "meta": { "annotations": { "instructions": "", "readonly": false, "destructive": true, "idempotent": false } } } ] ``` -------------------------------- ### Register Ability with Input Parameters (PHP) Source: https://github.com/wordpress/abilities-api/blob/trunk/docs/php-api.md Register an ability that accepts input parameters, such as updating a WordPress option. This example requires the 'manage_options' capability for permission. ```php add_action( 'wp_abilities_api_init', 'my_plugin_register_update_option_ability' ); function my_plugin_register_update_option_ability() { wp_register_ability( 'my-plugin/update-option', array( 'label' => __( 'Update WordPress Option', 'my-plugin' ), 'description' => __( 'Updates the value of a WordPress option in the database. Requires manage_options capability.', 'my-plugin' ), 'category' => 'data-modification', 'input_schema' => array( 'type' => 'object', 'properties' => array( 'option_name' => array( 'type' => 'string', 'description' => 'The name of the option to update', 'minLength' => 1 ), 'option_value' => array( 'description' => 'The new value for the option' ) ), 'required' => array( 'option_name', 'option_value' ), 'additionalProperties' => false ), 'output_schema' => array( 'type' => 'object', 'properties' => array( 'success' => array( 'type' => 'boolean', 'description' => 'Whether the option was successfully updated' ), 'previous_value' => array( 'description' => 'The previous value of the option' ) ) ), 'execute_callback' => function( $input ) { $option_name = $input['option_name']; $new_value = $input['option_value']; $previous_value = get_option( $option_name ); $success = update_option( $option_name, $new_value ); return array( 'success' => $success, 'previous_value' => $previous_value ); }, 'permission_callback' => function() { return current_user_can( 'manage_options' ); }, 'meta' => array( 'annotations' => array( 'destructive' => false, 'idempotent' => true ), ), )); } ``` -------------------------------- ### List Abilities Request Source: https://github.com/wordpress/abilities-api/blob/trunk/docs/rest-api.md Example cURL request to list all available abilities via the REST API. Supports pagination and category filtering. ```bash curl https://example.com/wp-json/wp-abilities/v1/abilities ``` -------------------------------- ### Discover and Execute Abilities in JavaScript Source: https://github.com/wordpress/abilities-api/blob/trunk/packages/client/README.md Import and use core functions to get all abilities, a specific ability, or execute an ability with parameters. Ensure the client is correctly imported or available in the global scope. ```javascript const { getAbilities, getAbility, executeAbility } = wp.abilities; // or import { getAbilities, getAbility, executeAbility } from '@wordpress/abilities'; depending on your setup // Get all abilities const abilities = await getAbilities(); // Get a specific ability const ability = await getAbility( 'my-plugin/my-ability' ); // Execute an ability const result = await executeAbility( 'my-plugin/my-ability', { param1: 'value1', param2: 'value2', } ); ``` -------------------------------- ### Retrieve a Category Response Source: https://github.com/wordpress/abilities-api/blob/trunk/docs/rest-api.md Example JSON response for a single category. Includes slug, label, description, meta, and links. ```json { "slug": "data-retrieval", "label": "Data Retrieval", "description": "Abilities that retrieve and return data from the WordPress site.", "meta": {}, "_links": { "self": [ { "href": "https://example.com/wp-json/wp-abilities/v1/categories/data-retrieval" } ], "collection": [ { "href": "https://example.com/wp-json/wp-abilities/v1/categories" } ], "abilities": [ { "href": "https://example.com/wp-json/wp-abilities/v1?category=data-retrieval" } ] } } ``` -------------------------------- ### Run PHPUnit Tests with Coverage Source: https://github.com/wordpress/abilities-api/blob/trunk/CONTRIBUTING.md Generate a code coverage report for PHPUnit tests. Start the environment with coverage mode enabled. ```bash npm run env start -- --xdebug=coverage npm run test:php ``` -------------------------------- ### Registering a Category and an Ability Source: https://github.com/wordpress/abilities-api/blob/trunk/docs/intro.md This example demonstrates how to register a new ability category and then register an ability within that category using WordPress action hooks. ```APIDOC ## Registering a Category and an Ability ### Description This example demonstrates how to register a new ability category and then register an ability within that category using WordPress action hooks. ### Functions - `add_action( 'wp_abilities_api_categories_init', 'my_plugin_register_category' )`: Hook to register a new ability category. - `wp_register_ability_category( $slug, $args )`: Registers a new ability category. - `add_action( 'wp_abilities_api_init', 'my_plugin_register_ability' )`: Hook to register a new ability. - `wp_register_ability( $ability_id, $args )`: Registers a new ability. ### Category Registration Arguments (`$args` for `wp_register_ability_category`) - **label** (string) - Required - The human-readable name for the category. - **description** (string) - Optional - A description of the category. ### Ability Registration Arguments (`$args` for `wp_register_ability`) - **label** (string) - Required - The human-readable name for the ability. - **description** (string) - Optional - A description of the ability. - **category** (string) - Required - The slug of the category this ability belongs to. - **input_schema** (array) - Optional - Defines the schema for the ability's input. - **output_schema** (object) - Optional - Defines the schema for the ability's output. - **type** (string) - The data type of the output (e.g., 'object', 'array'). - **properties** (object) - An object defining the properties of the output if the type is 'object'. - **site_name** (string) - The name of the WordPress site. - **site_url** (string) - The URL of the WordPress site. - **active_theme** (string) - The active theme of the WordPress site. - **active_plugins** (array) - List of active plugins on the WordPress site. - **php_version** (string) - The PHP version of the WordPress site. - **wordpress_version** (string) - The WordPress version of the site. - **execute_callback** (string) - Required - The name of the function to execute when the ability is called. - **permission_callback** (callback) - Required - A callback function that determines if the current user has permission to execute the ability. - **meta** (array) - Optional - Additional metadata for the ability. - **show_in_rest** (boolean) - Indicates if the ability should be shown in the REST API. ### Example Usage ```php // First, register a category, or use one of the existing categories. add_action( 'wp_abilities_api_categories_init', 'my_plugin_register_category'); function my_plugin_register_category(){ wp_register_ability_category( 'site-information', array( 'label' => __( 'Site Information', 'my-plugin' ), 'description' => __( 'Abilities that provide information about the WordPress site.', 'my-plugin' ), )); } // Then, register an ability in that category add_action( 'wp_abilities_api_init', 'my_plugin_register_ability'); function my_plugin_register_ability(){ wp_register_ability( 'my-plugin/site-info', array( 'label' => __( 'Site Info', 'my-plugin' ), 'description' => __( 'Returns information about this WordPress site', 'my-plugin' ), 'category' => 'site-information', 'input_schema' => array(), 'output_schema' => array( 'type' => 'object', 'properties' => array( 'site_name' => array( 'type' => 'string', 'description' => __( 'The name of the WordPress site', 'my-plugin' ) ), 'site_url' => array( 'type' => 'string', 'description' => __( 'The URL of the WordPress site', 'my-plugin' ) ), 'active_theme' => array( 'type' => 'string', 'description' => __( 'The active theme of the WordPress site', 'my-plugin' ) ), 'active_plugins' => array( 'type' => 'array', 'items' => array( 'type' => 'string' ), 'description' => __( 'List of active plugins on the WordPress site', 'my-plugin' ) ), 'php_version' => array( 'type' => 'string', 'description' => __( 'The PHP version of the WordPress site', 'my-plugin' ) ), 'wordpress_version' => array( 'type' => 'string', 'description' => __( 'The WordPress version of the site', 'my-plugin' ) ) ), ), 'execute_callback' => 'my_plugin_get_siteinfo', 'permission_callback' => function( $input ) { return current_user_can( 'manage_options' ); }, 'meta' => array( 'show_in_rest' => true, ), ) ); } ``` ``` -------------------------------- ### Registering an Ability with a Custom Ability Class Source: https://github.com/wordpress/abilities-api/blob/trunk/docs/php-api.md This example demonstrates how to define a custom ability class that extends WP_Ability and then register an ability using this custom class via the 'ability_class' parameter in wp_register_ability. ```APIDOC ## Registering an Ability with a Custom Ability Class ### Description This section details how to create and utilize a custom PHP class that extends `WP_Ability` to define a new ability. It shows how to override methods like `do_execute` for custom logic and how to register this custom ability using the `ability_class` parameter in the `wp_register_ability` function. ### Method `wp_register_ability` (within `wp_abilities_api_init` action hook) ### Parameters for `wp_register_ability` - **`my-plugin/validate-post`** (string) - The unique identifier for the ability. - **`array`** (array) - An array of arguments to configure the ability: - **`label`** (string) - Human-readable name for the ability. - **`description`** (string) - A detailed explanation of what the ability does. - **`category`** (string) - The category the ability belongs to. - **`input_schema`** (array) - Defines the expected structure and types of the input data. - **`type`** (string) - Schema type (e.g., 'object'). - **`properties`** (array) - Defines the fields within the input object. - **`post_id`** (integer) - Required. The ID of the post to validate. - **`required`** (array) - List of required fields (e.g., ['post_id']). - **`additionalProperties`** (boolean) - Whether additional properties are allowed. - **`output_schema`** (array) - Defines the expected structure and types of the output data. - **`type`** (string) - Schema type (e.g., 'object'). - **`properties`** (array) - Defines the fields within the output object. - **`valid`** (boolean) - Whether the post is valid. - **`post_title`** (string) - The post title. - **`post_date`** (string) - The post publication date. - **`execute_callback`** (callable) - The function that performs the ability's core logic. - **`permission_callback`** (callable) - A callback function to check user permissions. - **`ability_class`** (string) - The name of the custom class to use for this ability (e.g., 'My_Plugin_Post_Validator_Ability'). ### Request Example ```php add_action( 'wp_abilities_api_init', 'my_plugin_register_post_validator_ability' ); function my_plugin_register_post_validator_ability() { wp_register_ability( 'my-plugin/validate-post', array( 'label' => __( 'Validate Post', 'my-plugin' ), 'description' => __( 'Validates that a post exists, is published, and returns its metadata.', 'my-plugin' ), 'category' => 'data-retrieval', 'input_schema' => array( 'type' => 'object', 'properties' => array( 'post_id' => array( 'type' => 'integer', 'description' => 'The ID of the post to validate', 'minimum' => 1 ) ), 'required' => array( 'post_id' ), 'additionalProperties' => false ), 'output_schema' => array( 'type' => 'object', 'properties' => array( 'valid' => array( 'type' => 'boolean', 'description' => 'Whether the post is valid' ), 'post_title' => array( 'type' => 'string', 'description' => 'The post title' ), 'post_date' => array( 'type' => 'string', 'description' => 'The post publication date' ) ) ), 'execute_callback' => function( $input ) { $post_id = $input['post_id']; $post = get_post( $post_id ); if ( ! $post ) { return new \WP_Error( 'invalid_post', __( 'The specified post does not exist.', 'my-plugin' ) ); } // Check if the post is published if ( 'publish' !== $post->post_status ) { return new \WP_Error( 'post_not_published', __( 'The specified post is not published.', 'my-plugin' ) ); } // If validation passes, return post information return array( 'valid' => true, 'post_title' => $post->post_title, 'post_date' => $post->post_date ); }, 'permission_callback' => function() { // Any logged-in user can validate posts return is_user_logged_in(); }, 'meta' => array( 'annotations' => array( 'readonly' => true, 'destructive' => false ) ), // Specify the custom ability class to use 'ability_class' => 'My_Plugin_Post_Validator_Ability' )); } /** * Custom ability class that adds logging. * * This example shows how to extend WP_Ability to add custom behavior * while still leveraging all the standard ability functionality. */ class My_Plugin_Post_Validator_Ability extends WP_Ability { /** * Override the do_execute method to add custom logging. * * This demonstrates how you can override methods from WP_Ability * to customize behavior before or after the standard execution. * * @param mixed $input Optional. The input data for the ability. * @return mixed|\WP_Error The result of the ability execution. */ protected function do_execute( $input = null ) { // Log the execution for debugging purposes error_log( sprintf( 'Executing ability: %s with input: %s', $this->get_name(), json_encode( $input ) ) ); // Call the parent's do_execute to run the normal execute_callback $result = parent::do_execute( $input ); // Log the result if ( is_wp_error( $result ) ) { error_log( sprintf( 'Ability %s failed: %s', $this->get_name(), $result->get_error_message() ) ); } else { error_log( sprintf( 'Ability %s completed successfully', $this->get_name() ) ); } return $result; } } ``` -------------------------------- ### List Categories Response Source: https://github.com/wordpress/abilities-api/blob/trunk/docs/rest-api.md Example JSON response for listing categories. Includes slug, label, description, meta, and links to related resources. ```json [ { "slug": "data-retrieval", "label": "Data Retrieval", "description": "Abilities that retrieve and return data from the WordPress site.", "meta": {}, "_links": { "self": [ { "href": "https://example.com/wp-json/wp-abilities/v1/categories/data-retrieval" } ], "collection": [ { "href": "https://example.com/wp-json/wp-abilities/v1/categories" } ], "abilities": [ { "href": "https://example.com/wp-json/wp-abilities/v1/?category=data-retrieval" } ] } } ] ``` -------------------------------- ### Execute Server-Side Ability (GET/POST) Source: https://context7.com/wordpress/abilities-api/llms.txt Use `executeAbility` to run server-side abilities. It automatically selects GET for read-only operations and POST for write operations. Handle potential errors like invalid permissions, input, or if the ability is not found. ```javascript import { executeAbility } from '@wordpress/abilities'; // Execute a read-only ability (uses GET internally) try { const siteInfo = await executeAbility( 'my-plugin/get-site-info' ); console.log( 'Site name:', siteInfo.name ); console.log( 'Site URL:', siteInfo.url ); } catch ( error ) { switch ( error.code ) { case 'ability_invalid_permissions': console.error( 'Access denied:', error.message ); break; case 'ability_invalid_input': console.error( 'Bad input:', error.message ); break; case 'rest_ability_not_found': console.error( 'Ability not registered or not exposed to REST.' ); break; default: console.error( 'Unexpected error:', error.message ); } } // Execute a write ability with input (uses POST internally) const result = await executeAbility( 'my-plugin/update-option', { option_name: 'blogname', option_value: 'My New Title', } ); console.log( 'Updated:', result.success, '| Previous:', result.previous_value ); ``` -------------------------------- ### Retrieve Ability Definition Source: https://github.com/wordpress/abilities-api/blob/trunk/docs/rest-api.md Use this endpoint to get the definition of a specific ability, including its name, label, description, and output schema. This is useful for understanding what an ability does and how to interact with it. ```bash curl https://example.com/wp-json/wp-abilities/v1/my-plugin/get-site-info ``` -------------------------------- ### Register Ability with Input and Permissions Source: https://context7.com/wordpress/abilities-api/llms.txt Registers an ability to update WordPress options, requiring specific input parameters and checking user permissions. This example demonstrates structured input validation and permission callbacks. ```php wp_register_ability( 'my-plugin/update-option', array( 'label' => __( 'Update WordPress Option', 'my-plugin' ), 'description' => __( 'Updates a named option in the WordPress database.', 'my-plugin' ), 'category' => 'content-management', 'input_schema' => array( 'type' => 'object', 'required' => array( 'option_name', 'option_value' ), 'additionalProperties' => false, 'properties' => array( 'option_name' => array( 'type' => 'string', 'minLength' => 1 ), 'option_value' => array(), // any type ), ), 'output_schema' => array( 'type' => 'object', 'properties' => array( 'success' => array( 'type' => 'boolean' ), 'previous_value' => array(), ), ), 'execute_callback' => function( array $input ) { $prev = get_option( $input['option_name'] ); $success = update_option( $input['option_name'], $input['option_value'] ); return array( 'success' => $success, 'previous_value' => $prev ); }, 'permission_callback' => function() { return current_user_can( 'manage_options' ); }, 'meta' => array( 'show_in_rest' => true, 'annotations' => array( 'destructive' => false, 'idempotent' => true ), ), ) ); ``` -------------------------------- ### Hook into Ability Execution Lifecycle with `wp_before_execute_ability` and `wp_after_execute_ability` Source: https://context7.com/wordpress/abilities-api/llms.txt Log ability execution start and end times, including input and results. This is useful for auditing, debugging, and performance monitoring. ```php // Log all ability executions with input and result add_action( 'wp_before_execute_ability', 'my_plugin_log_ability_start', 10, 2 ); function my_plugin_log_ability_start( string $ability_name, $input ): void { error_log( sprintf( '[Abilities] START %s | user=%d | input=%s', $ability_name, get_current_user_id(), wp_json_encode( $input ) ) ); } add_action( 'wp_after_execute_ability', 'my_plugin_log_ability_end', 10, 3 ); function my_plugin_log_ability_end( string $ability_name, $input, $result ): void { error_log( sprintf( '[Abilities] END %s | result=%s', $ability_name, wp_json_encode( $result ) ) ); } ``` -------------------------------- ### Build Plugin for Distribution Source: https://github.com/wordpress/abilities-api/blob/trunk/CONTRIBUTING.md Run this command to package the plugin for distribution. This typically creates a zip archive. ```bash npm run plugin-zip ``` -------------------------------- ### Build and Commit Package Source: https://github.com/wordpress/abilities-api/blob/trunk/docs/releasing-a-new-package-version.md Run clean and build scripts, then add and commit the newly created build files. ```bash run clean && npm run build ``` ```bash git add . && git commit -m "Add build files for the client package" ``` -------------------------------- ### Execute an ability via REST API Source: https://context7.com/wordpress/abilities-api/llms.txt This endpoint allows you to execute abilities. The HTTP method (GET, POST, DELETE) is determined by the ability's annotations. Input can be provided via URL parameters for GET requests or a JSON body for POST requests. ```bash # GET – read-only ability, no input curl -u 'admin:xxxx xxxx xxxx xxxx xxxx xxxx' \ 'https://example.com/wp-json/wp-abilities/v1/my-plugin/get-site-info/run' ``` ```bash # GET – read-only ability with URL-encoded JSON input # input = {"user_id":1} → URL-encode: %7B%22user_id%22%3A1%7D curl -u 'admin:xxxx xxxx xxxx xxxx xxxx xxxx' \ 'https://example.com/wp-json/wp-abilities/v1/my-plugin/get-user-info/run?input=%7B%22user_id%22%3A1%7D' ``` ```bash # POST – write ability with JSON body input curl -u 'admin:xxxx xxxx xxxx xxxx xxxx xxxx' \ -X POST \ -H 'Content-Type: application/json' \ -d '{"input":{"option_name":"blogname","option_value":"New Title"}}' \ 'https://example.com/wp-json/wp-abilities/v1/my-plugin/update-option/run' ``` ```bash # DELETE – destructive ability with URL-encoded input curl -u 'admin:xxxx xxxx xxxx xxxx xxxx xxxx' \ -X DELETE \ 'https://example.com/wp-json/wp-abilities/v1/my-plugin/delete-post/run?input=%7B%22post_id%22%3A123%7D' ``` -------------------------------- ### wp_before_execute_ability Source: https://github.com/wordpress/abilities-api/blob/trunk/docs/hooks.md Fires immediately before an ability gets executed, after permission checks have passed but before the execution callback is called. ```APIDOC ## wp_before_execute_ability ### Description Fires immediately before an ability gets executed, after permission checks have passed but before the execution callback is called. ### Parameters #### Path Parameters - `$ability_name` (string) - Required - The namespaced name of the ability being executed (e.g., `my-plugin/get-posts`). - `$input` (mixed) - Required - The input data passed to the ability. ### Request Example ```php add_action( 'wp_before_execute_ability', 'log_ability_execution', 10, 2 ); /** * Log each ability execution attempt. * @param string $ability_name The name of the ability being executed. * @param mixed $input The input data passed to the ability. */ function log_ability_execution( string $ability_name, $input ) { error_log( 'About to execute ability: ' . $ability_name ); if ( $input !== null ) { error_log( 'Input: ' . wp_json_encode( $input ) ); } } ``` ``` -------------------------------- ### Retrieve a Category Request Source: https://github.com/wordpress/abilities-api/blob/trunk/docs/rest-api.md Example cURL request to retrieve a specific category by its slug. Requires authentication. ```bash curl -u 'USERNAME:APPLICATION_PASSWORD' \ https://example.com/wp-json/wp-abilities/v1/categories/data-retrieval ``` -------------------------------- ### Run Abilities with `useSelect` and `executeAbility` Source: https://context7.com/wordpress/abilities-api/llms.txt Integrates with `@wordpress/data` to reactively subscribe to abilities and execute them. Ensure `@wordpress/abilities` is imported. ```javascript import { useSelect } from '@wordpress/data'; import { store as abilitiesStore, executeAbility } from '@wordpress/abilities'; import { useState } from '@wordpress/element'; function AbilityRunner() { const [ output, setOutput ] = useState( null ); const [ error, setError ] = useState( null ); // Reactively subscribe to abilities in a specific category const contentAbilities = useSelect( ( select ) => select( abilitiesStore ).getAbilities( { category: 'content-management' } ), [] ); // Reactively subscribe to a single ability const siteInfoAbility = useSelect( ( select ) => select( abilitiesStore ).getAbility( 'my-plugin/get-site-info' ), [] ); const handleRun = async () => { try { const result = await executeAbility( 'my-plugin/get-site-info' ); setOutput( result ); setError( null ); } catch ( err ) { setError( err.message ); } }; return (

Content Management Abilities ({ contentAbilities.length })

{ siteInfoAbility && ( ) } { output &&
{ JSON.stringify( output, null, 2 ) }
} { error &&

Error: { error }

}
); } ``` -------------------------------- ### Get Ability Definition Source: https://github.com/wordpress/abilities-api/blob/trunk/docs/rest-api.md Retrieves the definition of a specific ability, including its name, label, description, and output schema. ```APIDOC ## GET /wp-abilities/v1/(?P[a-z0-9-]+)/(?P[a-z0-9-]+) ### Description Retrieves the definition of a specific ability. ### Method GET ### Endpoint /wp-abilities/v1/(?P[a-z0-9-]+)/(?P[a-z0-9-]+) ### Parameters #### Path Parameters - **namespace** (string) - Required - The namespace part of the ability name. - **ability** (string) - Required - The ability name part. ### Request Example ```bash curl https://example.com/wp-json/wp-abilities/v1/my-plugin/get-site-info ``` ### Response #### Success Response (200) - **name** (string) - The full name of the ability (namespace/ability). - **label** (string) - A human-readable label for the ability. - **description** (string) - A description of what the ability does. - **category** (string) - The category the ability belongs to. - **output_schema** (object) - The JSON schema defining the output of the ability. - **meta** (object) - Metadata about the ability, including annotations like readonly, destructive, and idempotent. #### Response Example ```json { "name": "my-plugin/get-site-info", "label": "Get Site Information", "description": "Retrieves basic information about the WordPress site.", "category": "site-information", "output_schema": { "type": "object", "properties": { "name": { "type": "string", "description": "Site name" }, "url": { "type": "string", "format": "uri", "description": "Site URL" } } }, "meta": { "annotations": { "instructions": "", "readonly": true, "destructive": false, "idempotent": false } } } ``` ``` -------------------------------- ### Discover and List Abilities with JavaScript Client Source: https://github.com/wordpress/abilities-api/blob/trunk/docs/javascript-client.md Use `getAbilities` to fetch all registered abilities. You can filter them by category. This is useful for dynamically displaying available actions or checking permissions. ```javascript import { getAbilities } from '@wordpress/abilities'; const abilities = await getAbilities(); console.log(`Found ${abilities.length} abilities`); // List all abilities abilities.forEach(ability => { console.log(`${ability.name}: ${ability.description}`); }); // Get abilities in a specific category const dataAbilities = await getAbilities( { category: 'data-retrieval' } ); console.log( `Found ${ dataAbilities.length } data retrieval abilities` ); ``` -------------------------------- ### Execute an ability Source: https://context7.com/wordpress/abilities-api/llms.txt Executes a specific WordPress ability. The HTTP method (GET, POST, DELETE) is determined by the ability's annotations. ```APIDOC ## GET|POST|DELETE /wp-abilities/v1/{namespace}/{ability}/run ### Description Executes a specified ability identified by its namespace and ability name. The HTTP method used depends on the ability's `readonly` and `destructive` annotations. ### Method - **GET**: Used for read-only abilities without input, or with URL-encoded JSON input via the `input` query parameter. - **POST**: Used for abilities that are not read-only and accept input via a JSON request body. - **DELETE**: Used for destructive abilities, typically with URL-encoded JSON input via the `input` query parameter. ### Endpoint /wp-json/wp-abilities/v1/{namespace}/{ability}/run ### Parameters #### Query Parameters - **input** (string) - Optional - URL-encoded JSON string representing the input for the ability. Used with GET and DELETE methods. #### Request Body - **input** (object) - Required for POST requests - An object containing the input parameters for the ability. ### Request Example ```bash # GET – read-only ability, no input curl -u 'admin:xxxx xxxx xxxx xxxx xxxx xxxx' \ 'https://example.com/wp-json/wp-abilities/v1/my-plugin/get-site-info/run' # GET – read-only ability with URL-encoded JSON input # input = {"user_id":1} → URL-encode: %7B%22user_id%22%3A1%7D curl -u 'admin:xxxx xxxx xxxx xxxx xxxx xxxx' \ 'https://example.com/wp-json/wp-abilities/v1/my-plugin/get-user-info/run?input=%7B%22user_id%22%3A1%7D' # POST – write ability with JSON body input curl -u 'admin:xxxx xxxx xxxx xxxx xxxx xxxx' \ -X POST \ -H 'Content-Type: application/json' \ -d '{"input":{"option_name":"blogname","option_value":"New Title"}}' \ 'https://example.com/wp-json/wp-abilities/v1/my-plugin/update-option/run' # DELETE – destructive ability with URL-encoded input curl -u 'admin:xxxx xxxx xxxx xxxx xxxx xxxx' \ -X DELETE \ 'https://example.com/wp-json/wp-abilities/v1/my-plugin/delete-post/run?input=%7B%22post_id%22%3A123%7D' ``` ### Response #### Success Response (200) - The response format varies depending on the ability executed. It typically returns a JSON object with the results of the ability's operation. #### Error Response Example (403 Forbidden) ```json { "code": "ability_invalid_permissions", "message": "Ability \"my-plugin/update-option\" does not have necessary permission.", "data": { "status": 403 } } ``` ``` -------------------------------- ### Registering an Ability with Input Parameters Source: https://github.com/wordpress/abilities-api/blob/trunk/docs/php-api.md This snippet shows how to register an ability that accepts input parameters. It defines an input schema, an output schema, and an execution callback that uses the provided input. ```APIDOC ## Registering an Ability with Input Parameters ### Description Registers an ability named 'my-plugin/update-option' to update a WordPress option, requiring specific input parameters. ### Method `wp_register_ability` ### Parameters - **ability_name** (string): 'my-plugin/update-option' - **config** (array): - **label** (string): 'Update WordPress Option' - **description** (string): 'Updates the value of a WordPress option in the database. Requires manage_options capability.' - **category** (string): 'data-modification' - **input_schema** (object): Defines the structure and types of expected input. - type: 'object' - properties: - option_name (string): 'The name of the option to update', minLength: 1 - option_value (any): 'The new value for the option' - required: ['option_name', 'option_value'] - additionalProperties: false - **output_schema** (object): Defines the structure of the returned data. - type: 'object' - properties: - success (boolean): 'Whether the option was successfully updated' - previous_value (any): 'The previous value of the option' - **execute_callback** (callable): Function to execute, accepting input parameters. - **permission_callback** (callable): Function to check user permissions (e.g., `current_user_can('manage_options')`). - **meta** (object): Metadata for the ability. - annotations (object): - destructive (boolean): false - idempotent (boolean): true ### Example Usage (Conceptual) ```php add_action( 'wp_abilities_api_init', 'my_plugin_register_update_option_ability' ); function my_plugin_register_update_option_ability() { wp_register_ability( 'my-plugin/update-option', array( 'label' => __( 'Update WordPress Option', 'my-plugin' ), 'description' => __( 'Updates the value of a WordPress option in the database. Requires manage_options capability.', 'my-plugin' ), 'category' => 'data-modification', 'input_schema' => array( 'type' => 'object', 'properties' => array( 'option_name' => array( 'type' => 'string', 'description' => 'The name of the option to update', 'minLength' => 1 ), 'option_value' => array( 'description' => 'The new value for the option' ) ), 'required' => array( 'option_name', 'option_value' ), 'additionalProperties' => false ), 'output_schema' => array( 'type' => 'object', 'properties' => array( 'success' => array( 'type' => 'boolean', 'description' => 'Whether the option was successfully updated' ), 'previous_value' => array( 'description' => 'The previous value of the option' ) ) ), 'execute_callback' => function( $input ) { $option_name = $input['option_name']; $new_value = $input['option_value']; $previous_value = get_option( $option_name ); $success = update_option( $option_name, $new_value ); return array( 'success' => $success, 'previous_value' => $previous_value ); }, 'permission_callback' => function() { return current_user_can( 'manage_options' ); }, 'meta' => array( 'annotations' => array( 'destructive' => false, 'idempotent' => true ), ), )); } ``` ``` -------------------------------- ### Execute Ability (GET - With Input) Source: https://github.com/wordpress/abilities-api/blob/trunk/docs/rest-api.md Execute a read-only ability that requires input. The input must be URL-encoded JSON passed as a query parameter. ```bash curl "https://example.com/wp-json/wp-abilities/v1/my-plugin/get-user-info/run?input=%7B%22user_id%22%3A1%7D" ```