Repository navigation
Comments: Introduce a register_comment_type() API - #12311
adamsilverstein wants to merge 36 commits into
Conversation
Add a comment type registration API modeled on the post type and taxonomy APIs, a first step toward custom comment types. Introduce the WP_Comment_Type class and register_comment_type(), unregister_comment_type(), get_comment_type_object(), get_comment_types(), and comment_type_exists(). Register the built-in comment, pingback, trackback, and note types via create_initial_comment_types(), hooked on init at priority 0 and on change_locale so labels re-translate. The note type is marked internal. Make the comment_type() template tag fall back to a registered type's singular label for non-built-in types when no custom text is supplied. Built-in output and explicit overrides are unchanged. Registration provides labels and metadata only; it does not constrain the values stored in the comment_type column or alter WP_Comment_Query behavior. See #35214.
Cover register_comment_type(), unregister_comment_type(), get_comment_type_object(), get_comment_types(), comment_type_exists(), the WP_Comment_Type class, and the registered/unregistered actions and label filters. Verify the built-in types are registered and cannot be unregistered, and that the comment_type() template tag renders registered type labels while preserving built-in output. See #35214.
|
The following accounts have interacted with this PR and/or linked issues. I will continue to update these lists as activity occurs. 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. Props Bot commandsYou can trigger Props Bot actions by commenting on this PR:
|
|
Hi there! 👋 Thank you for your contribution to WordPress! 💖 It looks like this is your first pull request to No one monitors this repository for new pull requests. Pull requests must be attached to a Trac ticket to be considered for inclusion in WordPress Core. To attach a pull request to a Trac ticket, please include the ticket's full URL in your pull request description. Pull requests are never merged on GitHub. The WordPress codebase continues to be managed through the SVN repository that this GitHub repository mirrors. Please feel free to open pull requests to work on any contribution you are making. More information about how GitHub pull requests can be used to contribute to WordPress can be found in the Core Handbook. Please include automated tests. Including tests in your pull request is one way to help your patch be considered faster. To learn about WordPress' test suites, visit the Automated Testing page in the handbook. If you have not had a chance, please review the Contribute with Code page in the WordPress Core Handbook. The Developer Hub also documents the various coding standards that are followed:
Thank you, |
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. |
…abel. Omit 'label' from the WP_Comment_Type::set_props() defaults so the property stays null when not provided. A false default was treated as a supplied value by _get_custom_object_labels(), which overwrote the default name with false, leaving labels->name and label as false for any type registered without an explicit label. This mirrors WP_Post_Type and WP_Taxonomy, which omit 'label' from their defaults for the same reason. Add a regression test covering default labels for a label-less comment type. See #35214.
The default branch of comment_type() echoed a registered type's
singular_name label without escaping. Labels are developer-supplied
(via register_comment_type() or the comment_type_labels_{$type}
filter) and reach the public comment list unescaped, so wrap the
output in esc_html() to match the post type and taxonomy label
contract. Document that labels are stored unescaped and add a
regression test asserting an HTML payload in the label is escaped.
Expose registered comment types through a read-only `/wp/v2/comment-types` controller, mirroring the post types controller (`/wp/v2/types`). This lets REST clients discover the registered types and their labels, which the block editor's inline-commenting work needs in order to add and query comments by type. Add a `show_in_rest` argument to `WP_Comment_Type` (defaulting to the value of `public`, as `show_ui` does) to gate which types the endpoint exposes. The built-in `comment`, `pingback`, and `trackback` types are public and therefore visible; the internal `note` type is not. Builds on the registration API in WordPress#12311. See #35214.
Add reset_comment_types() to WP_UnitTestCase_Base, mirroring reset_post_types()/reset_taxonomies(), plus an _unregister_comment_type() helper. This removes the need for hand-rolled tear_down() cleanup loops in individual test classes, which never ran when an assertion failed first, and heals any test that mutates the built-in types.
…stration. Nothing in the comment type API consumes 'show_ui' yet; the admin list table work that would read it is still design-gated. Removing an argument after release is impossible while adding one later is trivial, so defer it to the PR that introduces the admin UI.
register_comment_type() previously overwrote an existing registration silently, matching register_post_type(). For built-in comment types that would let a plugin strip flags core relies on (for example rendering and query behavior), so reject those with _doing_it_wrong() and a WP_Error instead. Core's own repeated registrations on 'init' and 'change_locale' pass '_builtin' and remain allowed, and unregister_comment_type() already guards built-ins the same way. Custom (non-built-in) types keep silent-overwrite semantics, now pinned by a test alongside register -> unregister -> register.
- Replace the inaccurate 'upgrade routine' rationale on
register_comment_type() with the real reason registrations should not
be hooked before 'init' (translations must be loaded).
- Rewrite the 'public' and 'internal' docs to describe what core
actually does with them today instead of promising behavior that is
not implemented; note why 'public' defaults to true.
- Move the misplaced escaping paragraph in the
comment_type_labels_{$comment_type} filter docblock above the tags so
the code reference parser keeps it.
- Add the missing @SInCE 7.1.0 changelog entry to comment_type() for
the new singular-label fallback.
- Type get_comment_types() $args as array: a string would fatal in
wp_filter_object_list() on PHP 8.
- Note the deliberate i18n string reuse in create_initial_comment_types()
and include comment types in the _get_custom_object_labels() summary.
- Fix label docblock nits and @PARAM alignment.
_get_custom_object_labels() unconditionally derives 'name_admin_bar' and spawns 'all_items'/'archives' when a 'menu_name' is provided, all of which are meaningless for comment types. Strip them from the labels object unless explicitly provided at registration. Also expand test coverage for the registration API: name sanitization and the 20-character boundary, get_comment_types() operators and output keying, the label fallback chain, filter backfill of required labels, action arguments, non-scalar lookups, idempotent built-in registration, template output for legacy empty and built-in 'note' types, and make the reset_default_labels() test able to fail by poisoning the static cache. Add per-method @Covers tags.
reset_comment_types() unregistered only the types reporting _builtin false, so a test that registers a custom type with '_builtin' set left it in the registry for every test that followed - which then hit the built-in re-registration guard for a name it had never registered. Registering a comment type creates no hooks, rewrite rules, or meta boxes, so emptying the registry and re-running create_initial_comment_types() is both complete cleanup and simpler. See #35214.
…ype. The hierarchical property exists only so the shared label helper has a slot to resolve against, and comment types deliberately leave that slot null. set_props() copies every provided argument onto the object, though, so a plugin carrying `'hierarchical' => true` over from register_post_type() flipped the property and resolved name, singular_name, menu_name, and label to null. Nothing errored - the type was silently unlabeled, and comment_type()'s isset() check hid it. Force the property false alongside the other derived values. See #35214.
…ntract. WP_Comment_Query reads 'all', 'comments', and 'pings' as query tokens rather than as literal comment_type values, so a type registered under one of those names could never be queried for on its own. Reject them at registration instead of letting a plugin discover it later. The rest is contract that was implied but never written down, and the follow-up PRs in this stack each add another argument, so it is worth fixing the shape now rather than accumulating a register_post_type()-style cascade: each argument drives exactly one layer of behavior and never implies another, `internal` is the one that drives default query and count exclusion, and `show_in_rest` defaulting from `public` is the single cascade planned. Also document that '_builtin' is for core's own use, that unregistered types behave exactly as they did before this API existed, and that the registry is per-process rather than per-site. Pin the edges with tests: '_builtin' passed by a plugin both bypasses the re-registration guard and locks a custom type, built-in labels rebuild on a locale change, the accessors cope with the registry global not existing yet, and a registration survives switch_to_blog(). See #35214.
…ject. _get_custom_object_labels() writes every label it derives back onto the object it receives, including the post-type-only labels this function strips from its return value. Calling get_comment_type_labels() on an already registered comment type therefore polluted the registered object's labels with name_admin_bar, all_items, and archives, and a second call returned them, breaking the documented label set. The registration path masked this because set_props() reassigns labels from the return value immediately. Pass a copy of the object into the helper so the registered object is never touched, and pin the invariant with a repeated-call test. See #35214.
The internal argument's docs stated that internal types are excluded
from comment queries and counts through the
default_excluded_comment_types filter, but that filter is proposed
separately (see #65537) and does not exist in this change. A plugin
author following the argument contract would expect an exclusion that
never happens, and the {@see} tag pointed hook docs at a nonexistent
hook.
Describe the flag the way public is already described: what it is
meant to drive, with an explicit note that core does not act on it
yet. The wording can be tightened back up when the exclusion filter
lands.
See #35214.
Trunk now ships a `reaction` comment type for notes reactions and treats it like `note` throughout core (excluded from default queries, counts, and feeds). Without a registration, a plugin could claim the `reaction` key with its own labels and flags, or unregister it. Register it alongside `note` with the same internal, non-public, built-in arguments and its own labels. The built-in type count used by the idempotency test goes from four to five. See #35214.
Several doc blocks and inline comments added for the comment type API narrated design history and repeated the same rationale in more than one place. Trim them to what a caller or maintainer needs and fix an action doc that called itself a filter. See #35214.
Trunk is in the 7.2 beta, so these additions can no longer ship in 7.2.0.
…type(). The label fallback skipped every built-in type, so the new translatable "Note" and "Reaction" labels were never shown and those comments printed "Comment". Only 'comment' is now excluded, which keeps its output byte-for-byte identical; pingback and trackback still use their own switch cases. See #35214. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_018vwYjV8tHyBXmGYuAqCoA8
The built-in guard could be skipped by passing '_builtin' => true, so any plugin could replace 'note' with internal => false. Core now clears its own built-ins before re-registering them on 'init' and 'change_locale', which lets the guard reject every re-registration of a built-in type. The args filters can no longer flip '_builtin' either way. Keys that sanitize_key() would change, such as 'Review', are now rejected. They were silently rewritten before, so the registered key no longer matched the stored comment_type value or the key callers used for lookups. get_comment_type_labels() builds its three labels directly instead of borrowing the post type helper. That removes the clone, the forced 'hierarchical' property and the post-type label cleanup, and stops future post type labels from leaking into comment types. New functions and the class also gain native parameter and return types where PHP 7.4 allows them. See #35214. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_018vwYjV8tHyBXmGYuAqCoA8
A typed parameter turns a bad argument, such as null, into a fatal TypeError instead of the WP_Error or null core APIs usually return. Untyped parameters keep the softer failure that register_post_type() and friends offer. Return types stay. See #35214. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_018vwYjV8tHyBXmGYuAqCoA8
wp_insert_comment() falls back to 'comment' when the type is empty(), and PHP treats the string '0' as empty. A type registered as '0' would report as existing while every comment saved with it is stored as 'comment', so registration now refuses it. See #35214. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_018vwYjV8tHyBXmGYuAqCoA8
An internal type should stay out of comment queries, counts and feeds without its plugin also having to filter the excluded set. The excluded types change read the registry behind existence checks to do that, which left code and a test that could not run until both changes landed. Hook a callback on 'default_excluded_comment_types' instead. The hook does nothing until that filter exists, so neither change has to check for the other. It runs at priority 0 so a plugin filtering at the default priority still sees the internal types and can remove one. See #35214, #65537.
|
Thanks @westonruter |
Review feedback on the comment type API asked for native property and parameter types, array shapes for the default labels, and for dropping query string arguments, which a new API has no reason to support. The properties and the constructor and set_props() parameters are now typed, and the default labels carry a PHPStan array shape. Typed properties turn a wrongly typed value into a TypeError, so set_props() now matches filtered arguments to the declared types before assigning them. register_comment_type() returns a WP_Error for non-array arguments instead of letting the constructor throw. See #35214. Claude-Session: https://claude.ai/code/session_018vwYjVKMar6Nquam1fh83Q
| * @param string $operator Optional. The logical operation to perform. 'or' means only one | ||
| * element from the array needs to match; 'and' means all elements | ||
| * must match; 'not' means no elements may match. Default 'and'. | ||
| * @return string[]|WP_Comment_Type[] An array of comment type names or objects. |
There was a problem hiding this comment.
Let's add a PHPStan conditional return for this, so that it returns string[] if $output === 'names'
There was a problem hiding this comment.
Good call, added in 65003f8.
Claude made the change, here is what it did:
get_comment_types()now has the same conditional return asget_post_types()andget_taxonomies():@phpstan-return ( $output is 'names' ? array<non-falsy-string, non-falsy-string> : array<non-falsy-string, WP_Comment_Type> )The keys are typed too since
wp_filter_object_list()preserves them, and a registered key can never be''or'0'.Two side effects worth a look:
wp_filter_object_list()returns a barearray, so the result gets an inline@varbefore it is returned. Without it level 10 reportsreturn.type._wp_exclude_internal_comment_types()no longer needs itsarray_filter( ..., 'is_string' ), which was only there to narrow the union.Separately, ecb5ffd removes
test_register_comment_type_rejects_non_array_arguments. With the nativearraytype on$argsfrom the batched suggestions, that call throws aTypeErrorbefore reaching the function body.
Co-authored-by: Weston Ruter <[email protected]>
The declared return was a union of names and objects, so callers could not tell which they had without narrowing it themselves. Tie the return type to $output, as get_post_types() and get_taxonomies() do, and drop the is_string filter in _wp_exclude_internal_comment_types() that only existed to narrow the union. wp_filter_object_list() returns a bare array, so the result is annotated before it is returned to satisfy the new type.
$args now has a native array type, so a query string raises a TypeError before the function body runs and the WP_Error path the test asserted no longer exists.
Stack: Custom Comment Types (#35214)
register_comment_type()registration API (this PR)/wp/v2/comment-typesendpointmap_meta_cap()render_callbackdisplay callbackis_pingping groupingdefault_excluded_comment_typesfilterwp_update_comment_counts()recount helper#12311 and #12310 are on WordPress/wordpress-develop; the rest are fork PRs targeting their parent branch and will retarget to trunk as their base lands.
Claude rewrote this description after a fresh review pass:
Trac ticket: https://core.trac.wordpress.org/ticket/35214
AI Use
Code and description both written with 🤖 Claude Code. I will review and test.