Skip to content

Add core/terms-query ability - #1099

Closed
jorgefilipecosta wants to merge 23 commits into
developfrom
add/core-terms-query
Closed

jorgefilipecosta wants to merge 23 commits into
developfrom
add/core-terms-query

Conversation

@jorgefilipecosta

@jorgefilipecosta jorgefilipecosta commented Oct 1, 2026 •

Copy link
Copy Markdown
Member

What?

Adds core/terms-query, a read-only ability for categories, tags, and other taxonomy terms (#1063).

How?

  • The ability lives in includes/Abilities/Terms/Terms.php, behind the Custom Abilities experiment.
  • Three modes: a term by id (optionally guarded by taxonomy), a term by taxonomy and slug, or the terms of one taxonomy filtered by search, include, exclude, parent, post, hide_empty, orderby, order, page, and per_page, returned as { terms, total, total_pages }.
  • Taxonomies opt in with show_in_abilities, like post types do for core/content-query. Show_In_Abilities marks category and post_tag.
  • Fields: id, count, description, link, name, slug, taxonomy, and parent (hierarchical taxonomies only). The default set leaves out description and link, and id is always returned.

Testing Instructions

  1. Enable the Custom Abilities experiment.
  2. Run core/terms-query with { "taxonomy": "category" }, { "id": 1 }, and { "taxonomy": "category", "slug": "uncategorized" }.
  3. npm run test:php -- --filter 'Terms|Show_In_Abilities|Gated_Abilities'
  4. npm run test:e2e -- tests/e2e/specs/abilities/core-terms-query.spec.js

Changelog Entry

Added - New core/terms-query ability that reads categories, tags, and other taxonomy terms like the REST API terms endpoints.

Open WordPress Playground Preview

@github-actions

github-actions Bot commented Oct 1, 2026

Copy link
Copy Markdown

✅ WordPress Plugin Check Report

✅ Status: Passed

📊 Report

All checks passed! No errors or warnings found.


🤖 Generated by WordPress Plugin Check Action • Learn more about Plugin Check

@codecov

codecov Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.19820% with 8 lines in your changes missing coverage. Please review.
✅ Project coverage is 85.53%. Comparing base (fdd8296) to head (138a229).

Files with missing lines Patch % Lines
includes/Abilities/Terms/Terms.php 98.25% 7 Missing ⚠️
includes/Abilities/Show_In_Abilities.php 97.29% 1 Missing ⚠️
Additional details and impacted files
@@              Coverage Diff              @@
##             develop    #1099      +/-   ##
=============================================
+ Coverage      85.22%   85.53%   +0.30%     
- Complexity      4709     4807      +98     
=============================================
  Files            182      184       +2     
  Lines          17486    17913     +427     
=============================================
+ Hits           14902    15321     +419     
- Misses          2584     2592       +8     
Flag Coverage Δ
unit 85.53% <98.19%> (+0.30%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@jorgefilipecosta

Copy link
Copy Markdown
Member Author

Tested in the browser console on WordPress 7.1.2, from a post's editor with the Excerpt Generation and Custom Abilities experiments enabled (Excerpt Generation puts @wordpress/abilities and @wordpress/core-abilities in the import map).

Test data: categories Fruit (169) with children Apple (170, one post) and Citrus (171), Vegetables (172) and Uncategorized (1); tags Red (173, one post) and Green (174); post 32 in Apple and Red.

await ( await import( '@wordpress/core-abilities' ) ).ready;
const { executeAbility } = await import( '@wordpress/abilities' );

Query the terms of a taxonomy

await executeAbility( 'core/terms-query', { taxonomy: 'category' } );
// { terms: [
//   { id: 170, count: 1, name: 'Apple', slug: 'apple', taxonomy: 'category', parent: 169 },
//   { id: 171, count: 0, name: 'Citrus', slug: 'citrus', taxonomy: 'category', parent: 169 },
//   { id: 169, count: 0, name: 'Fruit', slug: 'fruit', taxonomy: 'category', parent: 0 },
//   { id: 1, count: 0, name: 'Uncategorized', slug: 'uncategorized', taxonomy: 'category', parent: 0 },
//   { id: 172, count: 0, name: 'Vegetables', slug: 'vegetables', taxonomy: 'category', parent: 0 },
// ], total: 5, total_pages: 1 }

await executeAbility( 'core/terms-query', { taxonomy: 'category', parent: 169, hide_empty: true } );
// { terms: [ { id: 170, count: 1, name: 'Apple', slug: 'apple', taxonomy: 'category', parent: 169 } ], total: 1, total_pages: 1 }

// Tags aren't hierarchical, so they have no parent.
await executeAbility( 'core/terms-query', { taxonomy: 'post_tag', post: 32 } );
// { terms: [ { id: 173, count: 1, name: 'Red', slug: 'red', taxonomy: 'post_tag' } ], total: 1, total_pages: 1 }

await executeAbility( 'core/terms-query', { taxonomy: 'category', orderby: 'id', order: 'desc', per_page: 2, page: 2 } );
// { terms: [
//   { id: 170, count: 1, name: 'Apple', slug: 'apple', taxonomy: 'category', parent: 169 },
//   { id: 169, count: 0, name: 'Fruit', slug: 'fruit', taxonomy: 'category', parent: 0 },
// ], total: 5, total_pages: 3 }

// The ID is always included.
await executeAbility( 'core/terms-query', { taxonomy: 'category', search: 'apple', fields: [ 'name', 'description', 'link' ] } );
// { terms: [ { id: 170, description: 'Crisp and sweet.', link: 'http://localhost:8896/?cat=170', name: 'Apple' } ], total: 1, total_pages: 1 }

await executeAbility( 'core/terms-query', { taxonomy: 'category', include: [ 171, 169 ], orderby: 'include' } );
// { terms: [
//   { id: 171, count: 0, name: 'Citrus', slug: 'citrus', taxonomy: 'category', parent: 169 },
//   { id: 169, count: 0, name: 'Fruit', slug: 'fruit', taxonomy: 'category', parent: 0 },
// ], total: 2, total_pages: 1 }

Get a single term by ID

await executeAbility( 'core/terms-query', { id: 170 } );
// { id: 170, count: 1, name: 'Apple', slug: 'apple', taxonomy: 'category', parent: 169 }

Get a single term by taxonomy and slug

await executeAbility( 'core/terms-query', { taxonomy: 'post_tag', slug: 'red' } );
// { id: 173, count: 1, name: 'Red', slug: 'red', taxonomy: 'post_tag' }

Errors

// A term outside the given taxonomy is denied the same way as a missing one.
await executeAbility( 'core/terms-query', { id: 173, taxonomy: 'category' } );
await executeAbility( 'core/terms-query', { id: 999999 } );
// Both reject with { code: 'rest_ability_cannot_execute', message: 'Sorry, you are not allowed to execute this ability.', data: { status: 403 } }

await executeAbility( 'core/terms-query', { taxonomy: 'category', post: 999999 } );
// Rejects with { code: 'terms_post_invalid_id', message: 'Invalid post ID.', data: { status: 400 } }

// The client rejects these before sending a request, with an Error whose code is 'ability_invalid_input'.
await executeAbility( 'core/terms-query', { id: 170, per_page: 5 } ); // Modes can't be mixed.
await executeAbility( 'core/terms-query', { slug: 'red' } ); // A slug needs a taxonomy.
await executeAbility( 'core/terms-query', { taxonomy: 'nav_menu' } ); // Not exposed to abilities.

@gziolo

gziolo commented Oct 2, 2026

Copy link
Copy Markdown
Member

See my #1063 (comment) – this duplicates efforts started by @muneeb-ashraf in #1084.

@jeffpaul

jeffpaul commented Oct 4, 2026

Copy link
Copy Markdown
Member

@jorgefilipecosta note that I'm holding off on requesting reviews until this comes out of draft status

@jeffpaul jeffpaul linked an issue Oct 4, 2026 that may be closed by this pull request
@jeffpaul jeffpaul added this to the 1.5.0 milestone Oct 4, 2026
…re-terms-query

# Conflicts:
#	tests/Integration/Includes/Abilities/Gated/Gated_AbilitiesTest.php
…re-terms-query

# Conflicts:
#	tests/Integration/Includes/Abilities/Show_In_AbilitiesTest.php
…re-terms-query

Develop's post type normalization (only `true` exposes a post type) now
runs through the shared object helpers and applies to taxonomies too.

# Conflicts:
#	includes/Abilities/Show_In_Abilities.php
#	tests/Integration/Includes/Abilities/Show_In_AbilitiesTest.php
…re-terms-query

The 1.5.0 release tagged develop's post type normalization; the tests
generalized here keep `@since 1.5.0` and note the taxonomy coverage
as `@since x.x.x`.

# Conflicts:
#	tests/Integration/Includes/Abilities/Show_In_AbilitiesTest.php
whyisjake added a commit that referenced this pull request Nov 6, 2026
Stacked on #1004. Part of the follow-up on [jeffpaul's
review](#1004 (comment)),
items 5–7: the demo prompts ("Find a gap", "Audit content") need to list
recent posts and filter them, and the workspace could only search by
keyword. This adds the read tools those prompts need.

## What changed

**`ai/search-content` lists and filters, not just searches.**
- **`search` is optional.** Without it, the newest posts come first.
- **New optional inputs:**
- `orderby`: `relevance` or `date`. It defaults to relevance with a
search term and to date without one.
- `tax`: `{ taxonomy, terms }`, a public taxonomy and up to 20 term
slugs or names.
- `date_after` / `date_before`: `YYYY-MM-DD`, with both end days
included.
  - `has_featured_image`: `true` or `false`.
- **Each row also returns** `terms` (names keyed by taxonomy) and
`has_featured_image`.
- **Unchanged:** the per-post read check, the `examined`/`withheld`
counts the transcript's trace reads, and the 20-post page cap.

**A filter never widens the list.** Each of these is an error rather
than being ignored:
- a taxonomy the ability doesn't list (an unknown or private one);
- a `tax` value that isn't an object;
- a date that isn't a real day, such as `2026-02-31`. WP_Date_Query
would otherwise read it as 1970-01-01.

A term the taxonomy doesn't have matches no posts.

Only publicly viewable taxonomies attached to a post type exposed to
abilities can be filtered by or appear in a row's `terms`. A post has a
featured image when its `_thumbnail_id` is a positive number, the same
test `has_post_thumbnail()` uses for the row. Boolean and list inputs
are read as typed values or as the strings a GET request carries.

**New `ai/list-terms`.**
- Lists the terms of those same public taxonomies, with each term's
`name`, `slug` and published-post `count`.
- Defaults to categories and tags. `orderby` is `name` or `count`,
`hide_empty` defaults to true, and `per_page` is capped at 100.
- It's read-only, not destructive, `open_world: false`, and requires an
authenticated user.
- It stands in until `core/terms-query` (#1099 / #1084) lands here, as
the plan says.

**Tool list and policy:**
- Both abilities are on `Tool_Selector::DEFAULT_CANDIDATES`.
- `core/settings-get`, the name WordPress 7.2 gives the settings reader,
is added to `Tool_Policy::NEVER_ADMITTED` beside the old
`core/read-settings` (plan KTD9). The gap was hidden only because core
leaves out `open_world`.

**Structure.** The filter clauses and taxonomy discovery live in a new
`Search_Filters` class, shared by both abilities and resolved once per
call. `docs/experiments/ai-workspace.md` covers the new inputs, the new
ability and the never-admitted list.

## Tests

PHPUnit, `Search_ContentTest`:
- New:
  - "test_without_a_search_term_lists_newest_first"
  - "test_search_orders_by_relevance_unless_asked_for_date"
- "test_filters_by_term_date_range_and_featured_image": the fixtures
cover every combination of tag, year and thumbnail.
  - "test_date_range_includes_both_end_days"
  - "test_rows_carry_terms_and_featured_image"
  - "test_unknown_term_matches_no_posts"
  - "test_unknown_or_private_taxonomy_is_a_validation_error" (guard)
-
"test_execute_callback_refuses_an_unknown_taxonomy_without_schema_validation"
  - "test_listing_without_a_term_withholds_an_unreadable_post"
  - "test_an_impossible_date_is_refused"
  - "test_execute_callback_refuses_a_tax_filter_that_is_not_an_object"
  - "test_a_zero_thumbnail_id_counts_as_no_featured_image"
  - "test_private_taxonomy_terms_stay_off_rows" (guard)
- Updated:
  - "test_input_schema_caps_per_page": `search` is no longer required.
-
"test_search_with_no_term_reports_no_withheld_count_when_a_post_type_was_dropped":
comment wording only.

PHPUnit, new `List_TermsTest`, 8 tests:
- read-only and local annotations;
- ordering by count;
- leaving empty terms out by default;
- categories and tags by default;
- unknown and private taxonomies refused, through the schema and the
callback;
- the cap and total;
- a logged-out request refused.

PHPUnit, new `Search_Content_RestTest`, 2 guard tests:
- "test_search_filters_are_honoured_from_a_query_string"
- "test_list_terms_reads_its_inputs_from_a_query_string"

PHPUnit, `Tool_PolicyTest`:
- New: "test_settings_get_is_withheld_with_perfect_annotations".
- Updated:
"test_shipped_withheld_list_covers_the_sensitive_core_abilities".

`Tool_PolicyTest` and `Tool_SelectorTest` now include `ai/list-terms` in
the curated surface they assert against.

What failed before the change:
- On #1004's code, 11 search and policy tests fail, and `List_TermsTest`
can't load without its class.
- On the first commit (04bddc8), the impossible-date, non-object-`tax`
and zero-thumbnail tests fail.
- The tests marked "(guard)" pass on the earlier code too:
- The unknown-taxonomy test passes because the old schema refused any
`tax` input.
- The two REST tests pass because, on WordPress 7.1.4, the abilities
REST endpoint already converts query-string values to the schema's
types.
- The private-taxonomy test passes because the first commit already kept
those terms off the row.

Also run, on WordPress 7.1.4:
- **Full PHPUnit suite:** 3091 tests passed, 57 skipped. After one final
type-narrowing change for PHPStan, I re-ran only the 53 search and terms
tests, which pass.
- **e2e:** the `ai-workspace*` specs, plus the Abilities Explorer and
custom abilities specs. 45 passed (Chromium).
- **PHPStan:** no errors.
- **phpcs:**
  - clean on the changed source files;
- `Tool_PolicyTest` and `Tool_SelectorTest` have the same counts as the
base;
- the new `Search_Content_RestTest` has the same 3 errors as the
existing `Content_RestTest`, from the same REST-server setup.

Not covered:
- The plan's live check isn't done. It asks the "Find a gap" and "Audit
content" prompts, on a seeded site, to produce real tool calls that
return the expected posts. That needs a live model, and the e2e suite
mocks the provider. U10 covers the demo prompts end to end.
- The 20-term cap on a `tax` filter has no test.
- WordPress 7.0.x isn't covered. The REST coercion above was checked on
7.1.4 only, so the string-input parsing is what covers older cores.

## Code review

ce-code-review ran at full depth on the first commit (04bddc8), run
`20261105-103226-768518a0`.
- **Reviewers:** correctness, security, adversarial, testing,
maintainability, performance and API contract.
- **Not run:** the cross-model pass, because no other provider's CLI is
installed, so the adversarial lens ran in-process. There are no project
standards files on this branch.
- **Verdict:** "Ready with fixes". The validator confirmed three
findings, all addressed in 54a0d3e:
- **P1:** `Search_Content.php` grew from 1008 to 1276 lines. The filter
logic moved into `Search_Filters`, and the file is now 1142 lines. The
remaining growth is the new input and output schema.
- **P2:** string `has_featured_image` and comma-separated `tax.terms`
were dropped. Both are now read as typed values or strings.
- The validator confirmed this in the code, for callers that skip schema
validation.
- Through REST on WordPress 7.1.4 it doesn't reproduce: the new REST
tests pass on the first commit as well.
    - REST on 7.0.x wasn't measured.
- **P3:** `ai/list-terms` ignored string `hide_empty` and `taxonomy`.
Fixed the same way.
- **Residual risks the review kept:** all addressed in 54a0d3e:
  - duplicated taxonomy discovery;
  - per-row recomputation;
  - impossible dates;
  - a non-object `tax`;
  - the featured-image filter and row flag disagreeing on `0`.

One more: the `core/settings-get` name couldn't be checked against the
local wordpress-develop checkout. It is the name this plugin's 1.5.0
sync with WordPress 7.2 uses.

AI assistance: Yes. Tool(s): Claude Code (Claude Opus 5.5). Used for:
implementing the change and its tests, which I reviewed.

I've reviewed the changes, understand them and can explain them under
review. They have all been tested locally.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- wp-playground-preview:start -->
<a
href="https://playground.wordpress.net?blueprint-url=data:application/json,%7B%22preferredVersions%22%3A%7B%22wp%22%3A%22latest%22%7D%2C%22login%22%3Atrue%2C%22landingPage%22%3A%22%2Fwp-admin%2Fadmin.php%3Fpage%3Dai-wp-admin%22%2C%22steps%22%3A%5B%7B%22step%22%3A%22installPlugin%22%2C%22pluginData%22%3A%7B%22resource%22%3A%22url%22%2C%22url%22%3A%22https%3A%2F%2Fgithub.com%2FWordPress%2Fai%2Freleases%2Fdownload%2Fci-artifacts%2Fpr-1296-54a0d3ecca1a243cad855c3f65fbfe074dd5b46b.zip%22%7D%7D%5D%7D"
target="_blank" rel="noopener noreferrer">
<img
src="https://raw.githubusercontent.com/adamziel/playground-preview/refs/heads/trunk/assets/playground-preview-button.svg"
alt="Open WordPress Playground Preview" width="220" height="57" />
</a>
<!-- wp-playground-preview:end -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
@jeffpaul

Copy link
Copy Markdown
Member

Closing in favor of WordPress/abilities#10.

@jeffpaul jeffpaul closed this Nov 17, 2026
@jeffpaul jeffpaul removed this from the 1.6.0 milestone Nov 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

[Status] Duplicate This issue or pull request already exists

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add a core/terms-query ability (taxonomies, categories, tags)

4 participants