[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> abilities-api.php (source)

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


Generated : Wed Nov 4 08:20:38 2026 Cross-referenced by PHPXref