Feature #64990: Add filtering support to wp_get_abilities() via $args array#11531
Feature #64990: Add filtering support to wp_get_abilities() via $args array#11531Vedanshmini26 wants to merge 7 commits intoWordPress:trunkfrom
wp_get_abilities() via $args array#11531Conversation
|
The following accounts have interacted with this PR and/or linked issues. I will continue to update these lists as activity occurs. You can also manually ask me to refresh this list by adding the Core Committers: Use this line as a base for the props when committing in SVN: To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook. |
Test using WordPress PlaygroundThe changes in this pull request can previewed and tested using a WordPress Playground instance. WordPress Playground is an experimental project that creates a full WordPress instance entirely within the browser. Some things to be aware of
For more details about these limitations and more, check out the Limitations page in the WordPress Playground documentation. |
|
@Vedanshmini26, I missed your PR. This is a great start, and it covers the scope for extending I see several unrelated changes like |
f79e1f4 to
cc38e90
Compare
cc38e90 to
0350d8e
Compare
|
@gziolo I've removed the unrelated changes. Can you please check it now once? |
| $category = isset( $args['category'] ) ? (array) $args['category'] : array(); | ||
| $namespace = isset( $args['namespace'] ) && is_string( $args['namespace'] ) ? rtrim( $args['namespace'], '/' ) . '/' : ''; | ||
| $meta = isset( $args['meta'] ) && is_array( $args['meta'] ) ? $args['meta'] : array(); | ||
| $match_callback = isset( $args['match_callback'] ) && is_callable( $args['match_callback'] ) ? $args['match_callback'] : null; | ||
| $result_callback = isset( $args['result_callback'] ) && is_callable( $args['result_callback'] ) ? $args['result_callback'] : null; |
There was a problem hiding this comment.
This is worth double-checking with other similar functions to see whether silently dropping args with incorrect types is the established best practice.
There was a problem hiding this comment.
I checked against similar WordPress query functions — get_posts(), get_terms(), and WP_Query all silently cast or ignore args with incorrect types without triggering warnings. For example, get_posts() accepts 'category' as either a string or an integer and handles both without complaint. Our implementation follows the same established pattern: category is cast via (array), which safely handles both string and array inputs, while namespace, match_callback, and result_callback are guarded with is_string()/is_callable() checks and silently fall back to their defaults when the type is wrong.
If stricter developer feedback is desired, _doing_it_wrong() calls could be added in a follow-up, but silent dropping/casting is consistent with how WordPress core query functions have always behaved.
There was a problem hiding this comment.
Thank you for providing the clarification and references, some code examples for documentation purposes:
gziolo
left a comment
There was a problem hiding this comment.
All good now. I left some minor comments.
The only missing part is detailed unit test coverage, as noted earlier.
… and rename private helper to _wp_get_abilities_match_meta - Rename wp_get_abilities_match_meta() to _wp_get_abilities_match_meta() per WordPress private function naming convention - Add tests/phpunit/tests/abilities-api/wpGetAbilities.php covering: - category filter (single string, array OR logic, non-existent) - namespace filter (prefix match, trailing-slash normalisation, non-existent) - meta filter (single key, AND logic across keys, nested arrays, missing key) - match_callback per-item inclusion/exclusion and argument passing - wp_get_abilities_match filter hook exclusion and argument passing - result_callback result reshaping and argument passing - wp_get_abilities_result filter hook reshaping and argument passing - Combined category + meta and namespace + match_callback filters
…riable use declarations to one-per-line
…-per-line in result filter test
…_include in filter callbacks
|
@gziolo I've resolved the PR comments and added the unit test coverage. Can you please look into it? |
|
Yes, I will have a closer look later, but it should be good as is. Looking at WordPress 7.0 Release Party Updated Schedule, we can commit these changes in mid-May because WordPress |
wp_get_abilities() via $args array
| // Bail early when no filtering is requested. | ||
| if ( empty( $args ) ) { | ||
| return $abilities; |
There was a problem hiding this comment.
Consider dropping this early return so the full pipeline always runs.
The Trac ticket frames the two new filter hooks as the mechanism that lets plugins enforce universal rules — "A security plugin cannot enforce capability checks, the MCP adapter cannot gate visibility, and core cannot apply default scoping" — and concludes "Ecosystem hooks fire last at each level, so plugins always get the final say." The early bail prevents wp_get_abilities_match and wp_get_abilities_result from firing on the most common call path (wp_get_abilities() with no args), which is the path security/visibility plugins most need to participate in.
The perf cost of removing the bail is one foreach over an in-memory array — negligible next to anything else wp_get_abilities() callers do, and the filter is brand new so there is no BC concern with hooks firing more often.
For callers who genuinely want raw, unfiltered registry data, WP_Abilities_Registry::get_all_registered() is the right escape hatch (and is already @see'd in the docblock). Worth strengthening that pointer alongside this change.
Would also add a couple of tests asserting both filters fire when wp_get_abilities() is called with no args, so the contract is pinned.
| * @param WP_Ability $ability The ability instance being evaluated. | ||
| * @param array $args The full $args array passed to wp_get_abilities(). | ||
| */ | ||
| $include = (bool) apply_filters( 'wp_get_abilities_match', $include, $ability, $args ); |
There was a problem hiding this comment.
Naming nit worth resolving while the API is still pre-merge: this filter is wp_get_abilities_match but the variable it filters is $include, and the docblock describes the value as "whether to include the ability." One concept, two names — readers have to translate.
I'd vote we pick include and align everything to it. The action ("should this be included?") reads more naturally than the predicate ("did it match?"), and it avoids the cognitive collision with PHP 8's match expression.
Concrete proposal:
| Current | Proposed |
|---|---|
match_callback (arg key) |
item_include_callback |
wp_get_abilities_match (filter) |
wp_get_abilities_item_include |
$include (variable) |
unchanged |
The item_* / result_* pairing also makes the pipeline self-documenting: item_include_callback + wp_get_abilities_item_include (per-item scope) vs result_callback + wp_get_abilities_result (whole-array scope). When both keys appear in one $args array, the symmetry is genuinely clearer than match_callback + result_callback.
If we go this route, the rename cascades to:
- The
$argskey, filter hook name,@typeentry in the hash docblock, pipeline summary list (steps 2 & 3), and the inline// Step 2:comment. - All
test_match_callback_*/test_wp_get_abilities_match_*test methods and the section dividers in the test file.
| } | ||
|
|
||
| if ( ! empty( $request['namespace'] ) ) { | ||
| $query_args['namespace'] = $request['namespace']; |
There was a problem hiding this comment.
The refactor itself preserves existing behavior — test_filter_by_category, test_filter_by_nonexistent_category, and the implicit show_in_rest count in test_pagination_headers all pass after the change.
The gap is the new ?namespace= query parameter has no controller-layer tests. The PHP-layer filtering is well covered in wpGetAbilities.php, but the controller path adds behavior that should be pinned:
sanitize_keystrips/, so?namespace=foo/barcollapses tofoobar. That's safe (REST callers can only filter by base namespace, no path traversal), but the constraint isn't asserted.- The arg is only added to
$query_argswhen non-empty — easy to regress. ?namespace=must compose with the implicitshow_in_rest=truemeta filter. A namespace-matching ability withshow_in_rest=falsemust still be excluded — this isn't asserted anywhere.
Suggest adding three tests in wpRestAbilitiesV1ListController.php:
public function test_filter_by_namespace(): void {
$request = new WP_REST_Request( 'GET', '/wp-abilities/v1/abilities' );
$request->set_param( 'namespace', 'test' );
$response = $this->server->dispatch( $request );
$this->assertSame( 200, $response->get_status() );
$names = wp_list_pluck( $response->get_data(), 'name' );
$this->assertNotEmpty( $names, 'Expected at least one ability in the test namespace.' );
foreach ( $names as $name ) {
$this->assertStringStartsWith( 'test/', $name );
}
}
public function test_filter_by_nonexistent_namespace(): void {
$request = new WP_REST_Request( 'GET', '/wp-abilities/v1/abilities' );
$request->set_param( 'namespace', 'nonexistent' );
$response = $this->server->dispatch( $request );
$this->assertSame( 200, $response->get_status() );
$this->assertEmpty( $response->get_data() );
}
public function test_filter_by_namespace_still_respects_show_in_rest(): void {
// 'test/not-show-in-rest' is registered in the fixture with show_in_rest => false.
$request = new WP_REST_Request( 'GET', '/wp-abilities/v1/abilities' );
$request->set_param( 'namespace', 'test' );
$response = $this->server->dispatch( $request );
$names = wp_list_pluck( $response->get_data(), 'name' );
$this->assertNotContains( 'test/not-show-in-rest', $names );
}|
I left my remaining feedback to address. This is looking very solid! |
Core Trac Ticket: https://core.trac.wordpress.org/ticket/64990
Problem
wp_get_abilities() accepts no arguments and always returns the full registry. Callers who need a subset — by category, namespace, meta properties, or any combination — must retrieve all abilities and filter manually. As the number of registered abilities grows across core, plugins, and themes, several consumers have independently built ad-hoc filtering to work around this gap:
The MCP Adapter checks meta.mcp.public and meta.show_in_rest with its own array_filter pass
WooCommerce (v10.3+) introduced a woocommerce_mcp_include_ability filter that performs namespace-prefix matching (str_starts_with( $ability_id, 'woocommerce/' ))
The REST API controller already supports ?category filtering, but implements it with its own post-retrieval array_filter rather than delegating to wp_get_abilities()
This duplication signals a missing primitive. Each consumer reimplements the same patterns with slightly different semantics and no shared hook point for ecosystem-level participation.
Root Cause
wp_get_abilities() was shipped in 6.9 without filtering support. The REST API controller added its own array_filter logic for show_in_rest and category filtering instead of a shared primitive, creating a mismatch between what the PHP and REST APIs support. There was no per-item or result-level hook for plugins to participate in ability filtering without monkey-patching call sites.
Solution
Extends wp_get_abilities() to accept an optional $args array, following the established WordPress convention of array-based arguments (get_posts(), get_terms()). When called without arguments, behaviour is completely unchanged — no BC break.