Skip to content

Feature #64990: Add filtering support to wp_get_abilities() via $args array#11531

Open
Vedanshmini26 wants to merge 7 commits intoWordPress:trunkfrom
Vedanshmini26:filtering-wp-abilities
Open

Feature #64990: Add filtering support to wp_get_abilities() via $args array#11531
Vedanshmini26 wants to merge 7 commits intoWordPress:trunkfrom
Vedanshmini26:filtering-wp-abilities

Conversation

@Vedanshmini26
Copy link
Copy Markdown

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.

@github-actions
Copy link
Copy Markdown

github-actions Bot commented Apr 9, 2026

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 props-bot label.

Core Committers: Use this line as a base for the props when committing in SVN:

Props sheldorofazeroth, gziolo.

To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook.

@github-actions
Copy link
Copy Markdown

Test using WordPress Playground

The 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

  • All changes will be lost when closing a tab with a Playground instance.
  • All changes will be lost when refreshing the page.
  • A fresh instance is created each time the link below is clicked.
  • Every time this pull request is updated, a new ZIP file containing all changes is created. If changes are not reflected in the Playground instance,
    it's possible that the most recent build failed, or has not completed. Check the list of workflow runs to be sure.

For more details about these limitations and more, check out the Limitations page in the WordPress Playground documentation.

Test this pull request with WordPress Playground.

@gziolo
Copy link
Copy Markdown
Member

gziolo commented Apr 28, 2026

@Vedanshmini26, I missed your PR. This is a great start, and it covers the scope for extending wp_get_abilities() nicely. It would be very valuable to add unit tests that cover new functionality.


I see several unrelated changes like wp_lostpassword_form() or if ( current_user_can( $post_type_object->cap->read_private_posts ) ) { checks added in the codebase. Would you mind removing them?

@Vedanshmini26 Vedanshmini26 force-pushed the filtering-wp-abilities branch 2 times, most recently from f79e1f4 to cc38e90 Compare April 29, 2026 05:39
@Vedanshmini26 Vedanshmini26 force-pushed the filtering-wp-abilities branch from cc38e90 to 0350d8e Compare April 29, 2026 05:48
@Vedanshmini26
Copy link
Copy Markdown
Author

@gziolo I've removed the unrelated changes. Can you please check it now once?

Comment on lines +496 to +500
$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;
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is worth double-checking with other similar functions to see whether silently dropping args with incorrect types is the established best practice.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for providing the clarification and references, some code examples for documentation purposes:

Comment thread src/wp-includes/abilities-api.php Outdated
Copy link
Copy Markdown
Member

@gziolo gziolo left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
@Vedanshmini26
Copy link
Copy Markdown
Author

@gziolo I've resolved the PR comments and added the unit test coverage. Can you please look into it?

@gziolo
Copy link
Copy Markdown
Member

gziolo commented Apr 29, 2026

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 trunk is currently locked for bug fixes targeting WordPress 7.0.

@gziolo gziolo changed the title Feature #64990: Add filtering support to wp_get_abilities() via \$args array Feature #64990: Add filtering support to wp_get_abilities() via $args array Apr 29, 2026
Comment on lines +491 to +493
// Bail early when no filtering is requested.
if ( empty( $args ) ) {
return $abilities;
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 );
Copy link
Copy Markdown
Member

@gziolo gziolo May 6, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 $args key, filter hook name, @type entry 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'];
Copy link
Copy Markdown
Member

@gziolo gziolo May 6, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_key strips /, so ?namespace=foo/bar collapses to foobar. 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_args when non-empty — easy to regress.
  • ?namespace= must compose with the implicit show_in_rest=true meta filter. A namespace-matching ability with show_in_rest=false must 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 );
}

@gziolo
Copy link
Copy Markdown
Member

gziolo commented May 6, 2026

I left my remaining feedback to address. This is looking very solid!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants