| [ Index ] |
PHP Cross Reference of WordPress Trunk (Updated Daily) |
[Summary view] [Print] [Text view]
1 <?php 2 /** 3 * Abilities API: core functions for registering and managing abilities. 4 * 5 * The Abilities API provides a unified, extensible framework for registering 6 * and executing discrete capabilities within WordPress. An "ability" is a 7 * self-contained unit of functionality with defined inputs, outputs, permissions, 8 * and execution logic. 9 * 10 * ## Overview 11 * 12 * The Abilities API enables developers to: 13 * 14 * - Register custom abilities with standardized interfaces. 15 * - Define permission checks and execution callbacks. 16 * - Organize abilities into logical categories. 17 * - Validate inputs and outputs using JSON Schema. 18 * - Expose abilities to clients such as the REST API. 19 * 20 * ## Working with Abilities 21 * 22 * Abilities must be registered on the `wp_abilities_api_init` action hook. 23 * Attempting to register an ability outside of this hook will fail and 24 * trigger a `_doing_it_wrong()` notice. 25 * 26 * Example: 27 * 28 * function my_plugin_register_abilities(): void { 29 * wp_register_ability( 30 * 'my-plugin/export-users', 31 * array( 32 * 'label' => __( 'Export Users', 'my-plugin' ), 33 * 'description' => __( 'Exports user data to CSV format.', 'my-plugin' ), 34 * 'category' => 'data-export', 35 * 'execute_callback' => 'my_plugin_export_users', 36 * 'required_capabilities' => array( 'export' ), 37 * 'input_schema' => array( 38 * 'type' => 'string', 39 * 'enum' => array( 'subscriber', 'contributor', 'author', 'editor', 'administrator' ), 40 * 'description' => __( 'Limits the export to users with this role.', 'my-plugin' ), 41 * 'default' => 'subscriber', 42 * ), 43 * 'output_schema' => array( 44 * 'type' => 'string', 45 * 'description' => __( 'User data in CSV format.', 'my-plugin' ), 46 * ), 47 * 'meta' => array( 48 * 'public' => true, 49 * ), 50 * ) 51 * ); 52 * } 53 * add_action( 'wp_abilities_api_init', 'my_plugin_register_abilities' ); 54 * 55 * Every ability requires a category to group related abilities and improve discoverability. 56 * The `data-export` category must be registered first with `wp_register_ability_category()` 57 * on `wp_abilities_api_categories_init`, or the ability registration fails. 58 * 59 * Once registered, abilities can be checked, retrieved, and managed: 60 * 61 * // Checks if an ability is registered, and prints its label. 62 * if ( wp_has_ability( 'my-plugin/export-users' ) ) { 63 * $ability = wp_get_ability( 'my-plugin/export-users' ); 64 * 65 * echo $ability->get_label(); 66 * } 67 * 68 * // Gets all registered abilities. 69 * $all_abilities = wp_get_abilities(); 70 * 71 * // Unregisters when no longer needed. 72 * wp_unregister_ability( 'my-plugin/export-users' ); 73 * 74 * ## Best Practices 75 * 76 * - Always register abilities on the `wp_abilities_api_init` hook. 77 * - Use namespaced ability names to prevent conflicts. 78 * - Declare capabilities required for every execution in `required_capabilities`. 79 * - Check input-dependent permissions in `permission_callback`. 80 * - Provide an `input_schema` to ensure data integrity and document expected inputs. 81 * - Define an `output_schema` to describe return values and validate responses. 82 * - Return `WP_Error` objects for failures rather than throwing exceptions. 83 * - Use internationalization functions for all user-facing strings. 84 * 85 * @package WordPress 86 * @subpackage Abilities_API 87 * @since 6.9.0 88 */ 89 90 declare( strict_types = 1 ); 91 92 /** 93 * Registers a new ability using the Abilities API. It requires three steps: 94 * 95 * 1. Hook into the `wp_abilities_api_init` action. 96 * 2. Call `wp_register_ability()` with a namespaced name and configuration. 97 * 3. Provide an `execute_callback`. For permission checks, set `required_capabilities`, 98 * `permission_callback`, or both. 99 * 100 * Example: 101 * 102 * function my_plugin_register_abilities(): void { 103 * wp_register_ability( 104 * 'my-plugin/analyze-text', 105 * array( 106 * 'label' => __( 'Analyze Text', 'my-plugin' ), 107 * 'description' => __( 'Performs sentiment analysis on provided text.', 'my-plugin' ), 108 * 'category' => 'text-processing', 109 * 'input_schema' => array( 110 * 'type' => 'string', 111 * 'description' => __( 'The text to be analyzed.', 'my-plugin' ), 112 * 'minLength' => 10, 113 * ), 114 * 'output_schema' => array( 115 * 'type' => 'string', 116 * 'enum' => array( 'positive', 'negative', 'neutral' ), 117 * 'description' => __( 'The sentiment result: positive, negative, or neutral.', 'my-plugin' ), 118 * ), 119 * 'execute_callback' => 'my_plugin_analyze_text', 120 * 'required_capabilities' => array( 'edit_posts' ), 121 * 'permission_callback' => 'my_plugin_can_analyze_text', 122 * 'meta' => array( 123 * 'annotations' => array( 124 * 'readonly' => true, 125 * ), 126 * 'public' => true, 127 * ), 128 * ) 129 * ); 130 * } 131 * add_action( 'wp_abilities_api_init', 'my_plugin_register_abilities' ); 132 * 133 * The `text-processing` category must be registered first with 134 * `wp_register_ability_category()`, or the registration fails. 135 * 136 * On failure, this function returns `null` and calls `_doing_it_wrong()` with the reason. 137 * By default, the resulting notice is displayed when `WP_DEBUG` is enabled. 138 * 139 * ### Naming Conventions 140 * 141 * Ability names must follow these rules: 142 * 143 * - Include exactly one namespace and one ability name, separated by a single slash 144 * (e.g., `my-plugin/my-ability`). Nested namespaces are not supported. 145 * - Use only lowercase alphanumeric characters, dashes, and forward slashes. 146 * - Use descriptive, action-oriented names (e.g., `process-payment`, `generate-report`). 147 * 148 * ### Categories 149 * 150 * Every ability must specify a registered category. Categories group related abilities 151 * so clients can discover and retrieve relevant subsets. Plugins can reuse an existing 152 * category when appropriate, including categories registered by core. Custom categories must be 153 * registered on `wp_abilities_api_categories_init` before abilities that reference them 154 * are registered on `wp_abilities_api_init`: 155 * 156 * function my_plugin_register_categories(): void { 157 * wp_register_ability_category( 158 * 'text-processing', 159 * array( 160 * 'label' => __( 'Text Processing', 'my-plugin' ), 161 * 'description' => __( 'Abilities for analyzing and transforming text.', 'my-plugin' ), 162 * ) 163 * ); 164 * } 165 * add_action( 'wp_abilities_api_categories_init', 'my_plugin_register_categories' ); 166 * 167 * ### Input and Output Schemas 168 * 169 * Schemas define the expected structure, type, and constraints for ability inputs 170 * and outputs using JSON Schema syntax. They serve two critical purposes: automatic 171 * validation of data passed to and returned from abilities, and self-documenting 172 * API contracts for developers. 173 * 174 * WordPress implements a validator based on a subset of the JSON Schema Version 4 175 * specification (https://json-schema.org/specification-links.html#draft-4). 176 * For details on supported JSON Schema properties and syntax, see the 177 * related WordPress REST API Schema documentation: 178 * https://developer.wordpress.org/rest-api/extending-the-rest-api/schema/#json-schema-basics 179 * 180 * An input schema is required when passing non-null input. Without one, only `null` 181 * input is accepted and callbacks receive no arguments. When input is `null`, a 182 * top-level `default` in the input schema is applied before validation. 183 * 184 * An output schema is optional. When omitted, output schema validation is skipped. 185 * Define one to document and validate the result returned by the ability: 186 * 187 * 'input_schema' => array( 188 * 'type' => 'string', 189 * 'description' => __( 'The text to be analyzed.', 'my-plugin' ), 190 * 'minLength' => 10, 191 * ), 192 * 'output_schema' => array( 193 * 'type' => 'string', 194 * 'enum' => array( 'positive', 'negative', 'neutral' ), 195 * 'description' => __( 'The sentiment result: positive, negative, or neutral.', 'my-plugin' ), 196 * ), 197 * 198 * ### Callbacks 199 * 200 * #### Execute Callback 201 * 202 * The execute callback performs the ability's core functionality. It receives 203 * the input prepared by `WP_Ability::prepare_input()` when an input schema is 204 * defined, and no arguments otherwise. It returns either a result or `WP_Error` 205 * on failure. Exceptions thrown by execute or permission callbacks are caught 206 * and converted to a `WP_Error`. 207 * 208 * function my_plugin_analyze_text( string $input ): string|WP_Error { 209 * $score = My_Plugin::perform_sentiment_analysis( $input ); 210 * if ( is_wp_error( $score ) ) { 211 * return $score; 212 * } 213 * return My_Plugin::interpret_sentiment_score( $score ); 214 * } 215 * 216 * #### Required Capabilities and Permission Callback 217 * 218 * Declare only the minimum capabilities required for every execution in 219 * `required_capabilities`. Check additional capabilities that depend on the input 220 * in `permission_callback`. Declaring capabilities needed only for particular inputs 221 * can cause discovery to hide an ability the current user is allowed to execute 222 * with other inputs. 223 * 224 * Each required capability is checked with `current_user_can()` before the 225 * permission callback runs. The callback is optional when the list is non-empty. 226 * For an ability that everyone may execute, use `__return_true` as the callback 227 * with no required capabilities. 228 * 229 * The permission callback determines whether the ability can be executed and 230 * must return a boolean or `WP_Error`. When called through `WP_Ability::execute()`, 231 * it receives the same prepared input as the execute callback. Common use cases 232 * include checking user capabilities, validating API keys, or verifying system 233 * state. In the example above, every execution requires `edit_posts`, and the 234 * callback only adds the check that depends on the input: 235 * 236 * function my_plugin_can_analyze_text( string $input ): bool|WP_Error { 237 * // Only administrators can analyze long texts. 238 * if ( mb_strlen( $input ) > 5000 ) { 239 * return current_user_can( 'manage_options' ); 240 * } 241 * return true; 242 * } 243 * 244 * ### Execution Lifecycle 245 * 246 * Call `WP_Ability::execute()` to prepare the input, check permissions, invoke 247 * the execute callback, and validate output. It returns the result or a 248 * `WP_Error` on failure. Custom ability classes can override this behavior. 249 * 250 * Integrations that call `WP_Ability::check_permissions()` directly must pass it 251 * the input returned by `WP_Ability::prepare_input()`. 252 * 253 * Hooks run in this order, and processing stops at the first failure: 254 * 255 * 1. `wp_ability_invoked` action, with the raw input. 256 * 2. `wp_pre_execute_ability` filter, which can short-circuit the rest of execution. 257 * 3. `wp_ability_normalize_input` and `wp_ability_validate_input` filters, while the 258 * input is prepared. The input validation filter runs only when a non-empty input 259 * schema is defined. Sanitization has no filter. 260 * 4. `wp_ability_permission_result` filter. 261 * 5. `wp_before_execute_ability` action. 262 * 6. `wp_ability_execute_result` and `wp_ability_validate_output` filters. 263 * 7. `wp_after_execute_ability` action. 264 * 265 * ### Client Exposure 266 * 267 * Exposure flags do not grant execution permission. 268 * 269 * Set the high-level `public` flag to make an ability available to clients 270 * such as the REST API, MCP, or AI agents: 271 * 272 * 'meta' => array( 273 * 'public' => true, 274 * ), 275 * 276 * The `public` flag seeds the default for each per-channel flag. For the REST 277 * API it seeds `show_in_rest`, which lets the ability be invoked via HTTP 278 * requests. Set a per-channel flag directly to override that default. For 279 * example, keep a public ability out of the REST API: 280 * 281 * 'meta' => array( 282 * 'public' => true, 283 * 'show_in_rest' => false, 284 * ), 285 * 286 * @since 6.9.0 287 * @since 7.1.0 Added the `public` meta argument. 288 * @since 7.2.0 Added the `required_capabilities` argument. 289 * 290 * @see WP_Abilities_Registry::register() 291 * @see WP_Ability::execute() 292 * @see wp_register_ability_category() 293 * @see wp_unregister_ability() 294 * 295 * @param string $name The name of the ability. Must be a namespaced string containing 296 * a prefix, e.g., `my-plugin/my-ability`. Can only contain lowercase 297 * alphanumeric characters and dashes, with exactly one slash 298 * separating the namespace from the ability name. 299 * @param array<string, mixed> $args { 300 * An associative array of arguments for configuring the ability. 301 * 302 * @type string $label Required. The human-readable label for the ability. 303 * @type string $description Required. A detailed description of what the ability does 304 * and when it should be used. 305 * @type string $category Required. The registered ability category slug this ability belongs to. 306 * Custom categories must be registered via 307 * `wp_register_ability_category()` before registering the ability. 308 * @type callable $execute_callback Required. A callback function to execute when the ability is invoked. 309 * Receives optional mixed input data and must return either a result 310 * value (any type) or a `WP_Error` object on failure. 311 * @type callable $permission_callback Required unless `$required_capabilities` lists at least one capability. 312 * A callback function to check permissions before execution. 313 * Receives optional mixed input data (same as `execute_callback`) and 314 * must return `true`/`false` for simple checks, or `WP_Error` for 315 * detailed error responses. To let everyone run the ability, 316 * use `__return_true` with no required capabilities. The `public` 317 * meta flag doesn't affect this. It only controls where the 318 * ability is shown. 319 * @type list<string> $required_capabilities Optional. Minimum capabilities required for every execution of the 320 * ability, regardless of input. Each one is checked with 321 * `current_user_can()` before `permission_callback` runs. 322 * Must be a list of non-empty strings. Check input-dependent 323 * requirements in `permission_callback`. Default empty array. 324 * @type array<string, mixed> $input_schema Optional. JSON Schema definition for validating the ability's input. 325 * Must be a valid JSON Schema object defining the structure and 326 * constraints for input data. Used for automatic validation and 327 * API documentation. 328 * @type array<string, mixed> $output_schema Optional. JSON Schema definition for the ability's output. 329 * Describes the structure of successful return values from 330 * `execute_callback`. Used for documentation and validation. 331 * @type array<string, mixed> $meta { 332 * Optional. Additional metadata for the ability. 333 * 334 * @type array<string, bool|null> $annotations { 335 * Optional. Semantic annotations describing the ability's behavioral characteristics. 336 * These annotations are hints for tooling and documentation, not enforced behavior. 337 * Each annotation defaults to null, indicating that its behavior is unspecified. 338 * 339 * @type bool|null $readonly Optional. If true, the ability does not modify its environment. 340 * @type bool|null $destructive Optional. If true, the ability may perform destructive updates to its environment. 341 * If false, the ability performs only additive updates. 342 * @type bool|null $idempotent Optional. If true, calling the ability repeatedly with the same arguments 343 * will have no additional effect on its environment. 344 * } 345 * @type bool $public Optional. Whether the ability is meant to be available to 346 * clients such as the REST API, MCP, or AI agents. Seeds 347 * the default for per-channel flags like `$show_in_rest`. 348 * Defaults to false. 349 * @type bool $show_in_rest Optional. Whether to expose this ability in the REST API. 350 * When true, the ability can be invoked via HTTP requests. 351 * Default is the value of `$public` when set, false otherwise. 352 * } 353 * @type string $ability_class Optional. Fully-qualified custom class name to instantiate 354 * instead of the default `WP_Ability` class. The custom class 355 * must extend `WP_Ability`. Useful for advanced customization 356 * of ability behavior, including callback handling. The default 357 * execute and permission callback registration requirements 358 * are not enforced for custom classes. 359 * } 360 * @return WP_Ability|null The registered ability instance on success, `null` on failure. 361 * 362 * @phpstan-param lowercase-string&non-falsy-string $name 363 */ 364 function wp_register_ability( string $name, array $args ): ?WP_Ability { 365 if ( ! doing_action( 'wp_abilities_api_init' ) ) { 366 _doing_it_wrong( 367 __FUNCTION__, 368 sprintf( 369 /* translators: 1: wp_abilities_api_init, 2: string value of the ability name. */ 370 __( 'Abilities must be registered on the %1$s action. The ability %2$s was not registered.' ), 371 '<code>wp_abilities_api_init</code>', 372 '<code>' . esc_html( $name ) . '</code>' 373 ), 374 '6.9.0' 375 ); 376 return null; 377 } 378 379 $registry = WP_Abilities_Registry::get_instance(); 380 if ( null === $registry ) { 381 return null; 382 } 383 384 return $registry->register( $name, $args ); 385 } 386 387 /** 388 * Unregisters an ability from the Abilities API. 389 * 390 * Removes a previously registered ability from the global registry. Use this to 391 * disable abilities provided by other plugins or when an ability is no longer needed. 392 * 393 * Can be called at any time after the ability has been registered. 394 * 395 * Example: 396 * 397 * if ( wp_has_ability( 'other-plugin/some-ability' ) ) { 398 * wp_unregister_ability( 'other-plugin/some-ability' ); 399 * } 400 * 401 * @since 6.9.0 402 * 403 * @see WP_Abilities_Registry::unregister() 404 * @see wp_register_ability() 405 * 406 * @param string $name The name of the ability to unregister, including namespace prefix 407 * (e.g., 'my-plugin/my-ability'). 408 * @return WP_Ability|null The unregistered ability instance on success, `null` on failure. 409 */ 410 function wp_unregister_ability( string $name ): ?WP_Ability { 411 $registry = WP_Abilities_Registry::get_instance(); 412 if ( null === $registry ) { 413 return null; 414 } 415 416 return $registry->unregister( $name ); 417 } 418 419 /** 420 * Checks if an ability is registered. 421 * 422 * Use this for conditional logic and feature detection before attempting to 423 * retrieve or use an ability. 424 * 425 * Example: 426 * 427 * // Displays different UI based on available abilities. 428 * if ( wp_has_ability( 'premium-plugin/advanced-export' ) ) { 429 * echo 'Export with Premium Features'; 430 * } else { 431 * echo 'Basic Export'; 432 * } 433 * 434 * @since 6.9.0 435 * 436 * @see WP_Abilities_Registry::is_registered() 437 * @see wp_get_ability() 438 * 439 * @param string $name The name of the ability to check, including namespace prefix 440 * (e.g., 'my-plugin/my-ability'). 441 * @return bool `true` if the ability is registered, `false` otherwise. 442 */ 443 function wp_has_ability( string $name ): bool { 444 $registry = WP_Abilities_Registry::get_instance(); 445 if ( null === $registry ) { 446 return false; 447 } 448 449 return $registry->is_registered( $name ); 450 } 451 452 /** 453 * Retrieves a registered ability. 454 * 455 * Returns the ability instance for inspection or use. The instance provides access 456 * to the ability's configuration, metadata, and execution methods. 457 * 458 * Example: 459 * 460 * // Prints information about a registered ability. 461 * $ability = wp_get_ability( 'my-plugin/export-data' ); 462 * if ( $ability ) { 463 * echo $ability->get_label() . ': ' . $ability->get_description(); 464 * } 465 * 466 * @since 6.9.0 467 * 468 * @see WP_Abilities_Registry::get_registered() 469 * @see wp_has_ability() 470 * 471 * @param string $name The name of the ability, including namespace prefix 472 * (e.g., 'my-plugin/my-ability'). 473 * @return WP_Ability|null The registered ability instance, or `null` if not registered. 474 */ 475 function wp_get_ability( string $name ): ?WP_Ability { 476 $registry = WP_Abilities_Registry::get_instance(); 477 if ( null === $registry ) { 478 return null; 479 } 480 481 return $registry->get_registered( $name ); 482 } 483 484 /** 485 * Retrieves registered abilities, optionally filtered by the given arguments. 486 * 487 * When called without arguments, returns all registered abilities. When called 488 * with an $args array, returns only abilities that match every specified condition. 489 * In both cases, the callbacks and filters below can change the result. 490 * 491 * Filtering pipeline (executed in order): 492 * 493 * 1. Declarative filters (`category`, `namespace`, `meta`, `has_required_capabilities`) — 494 * per-item, AND logic between arg types. 495 * 2. `item_include_callback` — per-item, caller-scoped. Return true to include, false to exclude. 496 * 3. `wp_get_abilities_item_include` filter — per-item, ecosystem-scoped. Plugins can enforce 497 * inclusion rules for abilities that passed the declarative filters. 498 * 4. `result_callback` — on the full matched array, caller-scoped. Sort, slice, or reshape. 499 * 5. `wp_get_abilities_result` filter — on the full array, ecosystem-scoped. 500 * 501 * Steps 1–3 run inside a single loop over the registry — no extra iteration. 502 * 503 * Examples: 504 * 505 * // All abilities. 506 * $abilities = wp_get_abilities(); 507 * 508 * // Filter by category. 509 * $abilities = wp_get_abilities( array( 'category' => 'content' ) ); 510 * 511 * // Filter by namespace. 512 * $abilities = wp_get_abilities( array( 'namespace' => 'woocommerce' ) ); 513 * 514 * // Filter by meta. 515 * $abilities = wp_get_abilities( array( 'meta' => array( 'show_in_rest' => true ) ) ); 516 * 517 * // Abilities whose declared minimum capabilities the current user has. 518 * // Input-dependent permission checks still run when executing an ability. 519 * $abilities = wp_get_abilities( array( 'has_required_capabilities' => true ) ); 520 * 521 * // Combine filters (AND logic between arg types). 522 * $abilities = wp_get_abilities( array( 523 * 'category' => 'content', 524 * 'namespace' => 'core', 525 * 'meta' => array( 'show_in_rest' => true ), 526 * ) ); 527 * 528 * // Caller-scoped per-item callback. 529 * $abilities = wp_get_abilities( array( 530 * 'item_include_callback' => function ( WP_Ability $ability ) { 531 * return current_user_can( 'manage_options' ); 532 * }, 533 * ) ); 534 * 535 * // Caller-scoped result callback (sort + paginate). 536 * $abilities = wp_get_abilities( array( 537 * 'result_callback' => function ( array $abilities ) { 538 * uasort( $abilities, fn( $a, $b ) => strcasecmp( $a->get_label(), $b->get_label() ) ); 539 * return array_slice( $abilities, 0, 10, true ); 540 * }, 541 * ) ); 542 * 543 * The pipeline always runs, even when called with no arguments. This ensures that the 544 * `wp_get_abilities_result` filter always fires, giving plugins a reliable place to 545 * enforce universal shaping rules. 546 * For raw, unfiltered registry data that bypasses the filter pipeline entirely, use 547 * {@see WP_Abilities_Registry::get_all_registered()} directly. 548 * 549 * @since 6.9.0 550 * @since 7.1.0 Added the `$args` parameter for filtering support. 551 * @since 7.2.0 Added the `has_required_capabilities` argument. 552 * 553 * @see WP_Abilities_Registry::get_all_registered() 554 * 555 * @param array $args { 556 * Optional. Arguments to filter the returned abilities. Default empty array. 557 * Omitted filters do not restrict the results. 558 * 559 * @type string $category Optional. Filter by category slug. Only abilities whose category 560 * exactly matches the given slug are included. 561 * @type string $namespace Optional. Filter by ability namespace prefix. Pass the namespace 562 * without a trailing slash, e.g. `'woocommerce'` matches 563 * `'woocommerce/create-order'`. 564 * @type array $meta Optional. Filter by meta key/value pairs. All keys must exist 565 * and non-array values must match strictly, including their types. 566 * Nested arrays are matched recursively as subsets, e.g. 567 * `array( 'mcp' => array( 'public' => true ) )`. 568 * @type bool $has_required_capabilities Optional. Whether to leave out abilities whose required capabilities 569 * the current user doesn't have. Abilities without required 570 * capabilities pass this check but remain subject to other filters. 571 * Permission callbacks do not run, so inclusion does not guarantee 572 * execution permission. 573 * @type callable $item_include_callback Optional. A callback invoked per ability after declarative 574 * filters. Receives a WP_Ability instance, returns bool. 575 * Return true to include, false to exclude. 576 * @type callable $result_callback Optional. A callback invoked once on the full matched 577 * array. Receives WP_Ability[], must return WP_Ability[]. 578 * Use for sorting, slicing, or reshaping the result. 579 * } 580 * @return WP_Ability[] An array of registered WP_Ability instances, keyed by ability name 581 * unless reshaped by a callback or filter. Returns an empty array if 582 * the registry is unavailable. 583 */ 584 function wp_get_abilities( array $args = array() ): array { 585 $registry = WP_Abilities_Registry::get_instance(); 586 if ( null === $registry ) { 587 return array(); 588 } 589 590 $abilities = $registry->get_all_registered(); 591 592 $category = isset( $args['category'] ) && is_string( $args['category'] ) ? $args['category'] : ''; 593 $namespace = isset( $args['namespace'] ) && is_string( $args['namespace'] ) ? rtrim( $args['namespace'], '/' ) . '/' : ''; 594 $meta = isset( $args['meta'] ) && is_array( $args['meta'] ) ? $args['meta'] : array(); 595 $has_required_capabilities = ! empty( $args['has_required_capabilities'] ); 596 $item_include_callback = isset( $args['item_include_callback'] ) && is_callable( $args['item_include_callback'] ) ? $args['item_include_callback'] : null; 597 $result_callback = isset( $args['result_callback'] ) && is_callable( $args['result_callback'] ) ? $args['result_callback'] : null; 598 599 $matched = array(); 600 601 foreach ( $abilities as $name => $ability ) { 602 // Step 1a: Filter by category. 603 if ( '' !== $category && $ability->get_category() !== $category ) { 604 continue; 605 } 606 607 // Step 1b: Filter by namespace prefix. 608 if ( '' !== $namespace && ! str_starts_with( $ability->get_name(), $namespace ) ) { 609 continue; 610 } 611 612 // Step 1c: Filter by meta key/value pairs (AND logic, supports nested arrays). 613 if ( ! empty( $meta ) && ! _wp_get_abilities_match_meta( $ability->get_meta(), $meta ) ) { 614 continue; 615 } 616 617 // Step 1d: Leave out abilities whose required capabilities the current user doesn't have. 618 if ( $has_required_capabilities ) { 619 foreach ( $ability->get_required_capabilities() as $capability ) { 620 if ( ! current_user_can( $capability ) ) { 621 continue 2; 622 } 623 } 624 } 625 626 // Step 2: Caller-scoped per-item callback. 627 $include = true; 628 if ( null !== $item_include_callback ) { 629 $include = (bool) call_user_func( $item_include_callback, $ability ); 630 } 631 632 /** 633 * Filters whether an individual ability should be included in the result set. 634 * 635 * Fires after the declarative filters and the caller-scoped item_include_callback. 636 * Only abilities that pass the declarative filters reach this hook. It can override 637 * the caller-scoped callback's result. 638 * 639 * @since 7.1.0 640 * 641 * @param bool $include The caller-scoped callback's result, or true when no callback is provided. 642 * @param WP_Ability $ability The ability instance being evaluated. 643 * @param array $args The full $args array passed to wp_get_abilities(). 644 */ 645 $include = (bool) apply_filters( 'wp_get_abilities_item_include', $include, $ability, $args ); 646 647 if ( $include ) { 648 $matched[ $name ] = $ability; 649 } 650 } 651 652 // Step 4: Caller-scoped result callback. 653 if ( null !== $result_callback ) { 654 $matched = (array) call_user_func( $result_callback, $matched ); 655 } 656 657 /** 658 * Filters the full list of matched abilities after all per-item filtering is complete. 659 * 660 * Fires after the caller-scoped result_callback. Plugins can use this to sort, 661 * paginate, or reshape the final result set universally. 662 * 663 * @since 7.1.0 664 * 665 * @param WP_Ability[] $matched The matched abilities after all filtering. 666 * @param array $args The full $args array passed to wp_get_abilities(). 667 */ 668 return (array) apply_filters( 'wp_get_abilities_result', $matched, $args ); 669 } 670 671 /** 672 * Checks whether an ability's meta array matches a set of required key/value conditions. 673 * 674 * All conditions must match (AND logic). Supports nested arrays for structured meta, 675 * e.g. `array( 'mcp' => array( 'public' => true ) )`. Every condition key must exist, 676 * and non-array values are compared strictly, including their types. Extra meta keys 677 * are allowed at any level. 678 * 679 * @since 7.1.0 680 * @access private 681 * 682 * @param array $meta The ability's meta array. 683 * @param array $conditions The required key/value conditions to match against. 684 * @return bool True if all conditions match, false otherwise. 685 */ 686 function _wp_get_abilities_match_meta( array $meta, array $conditions ): bool { 687 foreach ( $conditions as $key => $value ) { 688 if ( ! array_key_exists( $key, $meta ) ) { 689 return false; 690 } 691 692 if ( is_array( $value ) ) { 693 if ( ! is_array( $meta[ $key ] ) || ! _wp_get_abilities_match_meta( $meta[ $key ], $value ) ) { 694 return false; 695 } 696 } elseif ( $meta[ $key ] !== $value ) { 697 return false; 698 } 699 } 700 701 return true; 702 } 703 704 /** 705 * Registers a new ability category. 706 * 707 * Ability categories provide a way to organize and group related abilities for better 708 * discoverability and management. Every ability requires a registered category. 709 * Custom categories must be registered before abilities that reference them. 710 * 711 * Ability categories must be registered on the `wp_abilities_api_categories_init` action hook. 712 * 713 * Example: 714 * 715 * function my_plugin_register_categories() { 716 * wp_register_ability_category( 717 * 'content-management', 718 * array( 719 * 'label' => __( 'Content Management', 'my-plugin' ), 720 * 'description' => __( 'Abilities for managing and organizing content.', 'my-plugin' ), 721 * ) 722 * ); 723 * } 724 * add_action( 'wp_abilities_api_categories_init', 'my_plugin_register_categories' ); 725 * 726 * On failure, this function returns `null` and calls `_doing_it_wrong()` with the reason. 727 * By default, the resulting notice is displayed when `WP_DEBUG` is enabled. 728 * 729 * @since 6.9.0 730 * 731 * @see WP_Ability_Categories_Registry::register() 732 * @see wp_register_ability() 733 * @see wp_unregister_ability_category() 734 * 735 * @param string $slug The unique slug for the ability category. Must contain lowercase 736 * alphanumeric segments separated by single dashes (e.g., 'data-export'), 737 * with no leading or trailing dash. 738 * @param array<string, mixed> $args { 739 * An associative array of arguments for the ability category. 740 * 741 * @type string $label Required. The human-readable label for the ability category. 742 * @type string $description Required. A description of what abilities in this category do. 743 * @type array<string, mixed> $meta Optional. Additional metadata for the ability category. 744 * } 745 * @return WP_Ability_Category|null The registered ability category instance on success, `null` on failure. 746 * 747 * @phpstan-param lowercase-string&non-empty-string $slug 748 */ 749 function wp_register_ability_category( string $slug, array $args ): ?WP_Ability_Category { 750 if ( ! doing_action( 'wp_abilities_api_categories_init' ) ) { 751 _doing_it_wrong( 752 __FUNCTION__, 753 sprintf( 754 /* translators: 1: wp_abilities_api_categories_init, 2: ability category slug. */ 755 __( 'Ability categories must be registered on the %1$s action. The ability category %2$s was not registered.' ), 756 '<code>wp_abilities_api_categories_init</code>', 757 '<code>' . esc_html( $slug ) . '</code>' 758 ), 759 '6.9.0' 760 ); 761 return null; 762 } 763 764 $registry = WP_Ability_Categories_Registry::get_instance(); 765 if ( null === $registry ) { 766 return null; 767 } 768 769 return $registry->register( $slug, $args ); 770 } 771 772 /** 773 * Unregisters an ability category. 774 * 775 * Removes a previously registered ability category from the global registry. Use this to 776 * disable ability categories that are no longer needed. 777 * 778 * Can be called at any time after the ability category has been registered. 779 * 780 * Example: 781 * 782 * if ( wp_has_ability_category( 'deprecated-category' ) ) { 783 * wp_unregister_ability_category( 'deprecated-category' ); 784 * } 785 * 786 * @since 6.9.0 787 * 788 * @see WP_Ability_Categories_Registry::unregister() 789 * @see wp_register_ability_category() 790 * 791 * @param string $slug The slug of the ability category to unregister. 792 * @return WP_Ability_Category|null The unregistered ability category instance on success, `null` on failure. 793 */ 794 function wp_unregister_ability_category( string $slug ): ?WP_Ability_Category { 795 $registry = WP_Ability_Categories_Registry::get_instance(); 796 if ( null === $registry ) { 797 return null; 798 } 799 800 return $registry->unregister( $slug ); 801 } 802 803 /** 804 * Checks if an ability category is registered. 805 * 806 * Use this for conditional logic and feature detection before attempting to 807 * retrieve or use an ability category. 808 * 809 * Example: 810 * 811 * // Displays different UI based on available ability categories. 812 * if ( wp_has_ability_category( 'premium-features' ) ) { 813 * echo 'Premium Features Available'; 814 * } else { 815 * echo 'Standard Features'; 816 * } 817 * 818 * @since 6.9.0 819 * 820 * @see WP_Ability_Categories_Registry::is_registered() 821 * @see wp_get_ability_category() 822 * 823 * @param string $slug The slug of the ability category to check. 824 * @return bool `true` if the ability category is registered, `false` otherwise. 825 */ 826 function wp_has_ability_category( string $slug ): bool { 827 $registry = WP_Ability_Categories_Registry::get_instance(); 828 if ( null === $registry ) { 829 return false; 830 } 831 832 return $registry->is_registered( $slug ); 833 } 834 835 /** 836 * Retrieves a registered ability category. 837 * 838 * Returns the ability category instance for inspection or use. The instance provides access 839 * to the ability category's configuration and metadata. 840 * 841 * Example: 842 * 843 * // Prints information about a registered ability category. 844 * $ability_category = wp_get_ability_category( 'content-management' ); 845 * if ( $ability_category ) { 846 * echo $ability_category->get_label() . ': ' . $ability_category->get_description(); 847 * } 848 * 849 * @since 6.9.0 850 * 851 * @see WP_Ability_Categories_Registry::get_registered() 852 * @see wp_has_ability_category() 853 * @see wp_get_ability_categories() 854 * 855 * @param string $slug The slug of the ability category. 856 * @return WP_Ability_Category|null The ability category instance, or `null` if not registered. 857 */ 858 function wp_get_ability_category( string $slug ): ?WP_Ability_Category { 859 $registry = WP_Ability_Categories_Registry::get_instance(); 860 if ( null === $registry ) { 861 return null; 862 } 863 864 return $registry->get_registered( $slug ); 865 } 866 867 /** 868 * Retrieves all registered ability categories. 869 * 870 * Returns an array of all ability category instances currently registered in the system. 871 * Use this for discovery, debugging, or building administrative interfaces. 872 * 873 * Example: 874 * 875 * // Prints information about all available ability categories. 876 * $ability_categories = wp_get_ability_categories(); 877 * foreach ( $ability_categories as $ability_category ) { 878 * echo $ability_category->get_label() . ': ' . $ability_category->get_description() . "\n"; 879 * } 880 * 881 * @since 6.9.0 882 * 883 * @see WP_Ability_Categories_Registry::get_all_registered() 884 * @see wp_get_ability_category() 885 * 886 * @return WP_Ability_Category[] An array of registered ability category instances, 887 * keyed by category slug. Returns an empty array if no ability categories 888 * are registered or if the registry is unavailable. 889 */ 890 function wp_get_ability_categories(): array { 891 $registry = WP_Ability_Categories_Registry::get_instance(); 892 if ( null === $registry ) { 893 return array(); 894 } 895 896 return $registry->get_all_registered(); 897 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
| Generated : Tue Nov 24 08:20:01 2026 | Cross-referenced by PHPXref |