Skip to content

Comments: Add filter for comment types excluded from queries by default - #12310

Open
adamsilverstein wants to merge 61 commits into
WordPress:trunkfrom
adamsilverstein:feature/65537-excluded-comment-types-filter
Open

adamsilverstein wants to merge 61 commits into
WordPress:trunkfrom
adamsilverstein:feature/65537-excluded-comment-types-filter

Conversation

@adamsilverstein

@adamsilverstein adamsilverstein commented Jun 24, 2026 •

Copy link
Copy Markdown
Member

Stack: Custom Comment Types (#35214)

PR Change Builds on
#12311 register_comment_type() registration API trunk
#51 REST /wp/v2/comment-types endpoint #12311
#52 Capabilities object (advisory) #12311
#55 Enforce type capabilities in map_meta_cap() adamsilverstein#52
#56 Type-aware REST moderation adamsilverstein#55
#57 Type-aware admin comment dimming adamsilverstein#56
#53 render_callback display callback #12311
#54 is_ping ping grouping adamsilverstein#53
👉 #12310 default_excluded_comment_types filter (this PR) trunk
#58 wp_update_comment_counts() recount helper #12310

#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.

I asked Claude to tighten up this description, here it is:

Comments: Add a filter for the comment types excluded from queries by default.

What

Adds a default_excluded_comment_types filter, read through a new wp_get_default_excluded_comment_types() accessor, so plugins can keep their own comment types out of standard comment lists, counts and feeds the same way core already does for note and reaction.

Fixes https://core.trac.wordpress.org/ticket/65537

Why

Core hides notes and reactions everywhere by hard-coding array( 'note', 'reaction' ) in a handful of places. A plugin with its own private comment type has no hook for that, so it has to rewrite the SQL through comments_clauses in every context and re-check it every release. The Alpaca issue tracker plugin keeps a whole library just for this: https://github.com/rareview/alpaca-issue-tracker/blob/main/lib/private-comments.php

This is a small, standalone step toward custom comment types (https://core.trac.wordpress.org/ticket/35214). Once the registry from #12311 lands, registering a type with 'internal' => true is enough and the filter is left for exceptions. That PR hooks the internal types onto this filter, so neither one depends on the other landing first.

add_filter( 'default_excluded_comment_types', function ( $types ) {
	$types[] = 'my_private_type';
	return $types;
} );

How

  • wp_get_default_excluded_comment_types() in wp-includes/comment.php starts from note and reaction, applies the filter, and normalizes the result: strings only, no empties or duplicates, and the WP_Comment_Query aliases (all, comment, comments, pings) stripped in any case.
  • wp_get_excluded_comment_types_clause() builds a prepared AND comment_type NOT IN (...) condition (column quoted with %i) for the queries that don't go through WP_Comment_Query.
  • Every place that excluded notes now reads the same set:
    • WP_Comment_Query::get_comment_ids() - an excluded type is still returned when requested by name, via type__in, an alias, or 'all'.
    • WP_Comment_Query::get_comments() and fill_descendants() - the resolved set is part of both cache keys, so a persistent object cache doesn't serve results from before the set changed.
    • The three comment feed queries in WP_Query.
    • wp_update_comment_count_now(), get_pending_comments_num() and get_lastcommentmodified(). The last one salts its cached date with the set, for the same reason as the query cache keys.
    • WP_Comments_List_Table - passes the set explicitly for an all request and leaves any other request to WP_Comment_Query, so a plugin can list its own excluded type via admin_comment_types_dropdown. Notes and reactions still can't be requested there.
    • get_page_of_comment() - with 'type' => 'all' it now leaves out the excluded types, so a comment's permalink points at the page it actually renders on. Before this, two notes ahead of a comment could push its cpage to the wrong page.

Excluding a type is a default-visibility setting, not access control. Over REST it only changes the default collection, and excluded types can still be queried explicitly. Only an exact type name lifts the exclusion: type=Note does not return notes.

Backward compatibility

With no filter the set is note and reaction, the same as trunk, so nothing changes for sites that don't use it. The one behavior change is the get_page_of_comment() fix above.

Stored comment_count values and the counts cache only refresh when a comment changes, so a plugin that starts excluding a type that already has comments should call wp_update_comment_count_now() for the affected posts on activation and deactivation. The filter docblock says so.

Testing

Test in Playground: https://playground.wordpress.net/wordpress.html?pr=12310

Automated:

vendor/bin/phpunit --group comment
vendor/bin/phpunit --group feeds
vendor/bin/phpunit --group query
vendor/bin/phpunit --group admin --filter Tests_Admin_wpCommentsListTable
vendor/bin/phpunit --group restapi --filter WP_Test_REST_Comments_Controller

Manual:

  1. Add the filter snippet above in an mu-plugin.
  2. wp comment create --comment_post_ID=1 --comment_type=my_private_type --comment_approved=1
  3. Check that the comment doesn't show on the post, in /comments/feed/, in Comments > All, or in the post's comment count (run wp eval 'wp_update_comment_count_now( 1 );' first).
  4. Visit wp-admin/edit-comments.php?comment_type=my_private_type and check that it is listed there.
  5. Remove the filter, recount, and check the comment comes back.

Out of scope / follow-ups

  • No registration object, labels, capabilities or admin UI - that is the rest of #35214.
  • The REST controller's notes-specific permission checks still name note and reaction directly. Those are about permissions, not default visibility, and are handled in the capability PRs.
  • A helper to recount posts after the excluded set changes is in the follow-up wp_update_comment_counts() PR.

Test in WordPress Playground

Trac ticket: https://core.trac.wordpress.org/ticket/35214, https://core.trac.wordpress.org/ticket/65537

Commit message

Claude drafted this commit message and I edited it:

Comments: Add a filter for comment types excluded by default.

Remove hard coding of the `note` and `reaction` comment types from standard comment lists, counts and feeds so plugins don't need to rewrite the SQL through `comments_clauses`.

Introduce a `default_excluded_comment_types` filter, read through the new `wp_get_default_excluded_comment_types()` function, and use that single set everywhere core previously named the types directly: `WP_Comment_Query`, the comment feed queries in `WP_Query`, `wp_update_comment_count_now()`, `get_pending_comments_num()`, `get_lastcommentmodified()`, `get_page_of_comment()` and `WP_Comments_List_Table`. An excluded type is still returned when a query requests it explicitly, so this controls default visibility and is not access control.

With no filter in place the set remains `note` and `reaction`, so behavior is unchanged, with one exception: `get_page_of_comment()` no longer counts excluded types, which fixes comment permalinks pointing at the wrong page when notes precede a comment. Stored comment counts only refresh when a comment changes, so a plugin that starts excluding a type with existing comments should recount the affected posts with `wp_update_comment_count_now()`.

Follow-up to [61105], [64488].

Props swissspidy, pfefferle, peterwilsoncc, s1m0nd.
Fixes #65537. See #35214.

Dev note

Claude drafted this dev note for the 7.3 field guide, I reviewed and edited:

New filter for comment types excluded from queries by default

WordPress 6.9 introduced the note comment type and 7.2 added reaction. Both are kept out of comment lists, counts and feeds, and until now core did that by naming the two types directly in each query. A plugin with its own private comment type had no equivalent and had to rewrite SQL through comments_clauses and similar filters in every context.

WordPress 7.3 adds the default_excluded_comment_types filter so plugins can add their own types to that set:

add_filter(
	'default_excluded_comment_types',
	function ( $types ) {
		$types[] = 'my_private_type';
		return $types;
	}
);

The set is read through the new wp_get_default_excluded_comment_types() function and applies to:

  • WP_Comment_Query, and so get_comments(), comments_template(), wp_count_comments() and the REST comments collection
  • the comment feeds
  • the stored post comment_count (wp_update_comment_count_now()) and get_pending_comments_num()
  • get_lastcommentmodified()
  • the Comments list table in the admin
  • get_page_of_comment() and comment permalinks

Things to know:

  • This sets default visibility, it is not access control. A query still returns an excluded type when it asks for it by exact name in type or type__in, or asks for 'type' => 'all'. Restrict who can read a type separately.
  • Stored comment counts are only refreshed when a comment changes. A plugin that starts or stops excluding a type that already has comments should call wp_update_comment_count_now() for the affected posts, for example on activation and deactivation.
  • The filter receives the excluded types only, with no query context. The counts, feeds and get_lastcommentmodified() have no query to pass, and a set that changed per query would make them disagree with the listed comments.
  • Values are literal comment_type values. The query aliases all, comment, comments and pings are ignored, as are empty and non-scalar values.
  • Queries that don't use WP_Comment_Query can get a prepared AND comment_type NOT IN ( ... ) condition from the new wp_get_excluded_comment_types_clause() function.

Two behavior changes for existing code:

  • get_page_of_comment() no longer counts excluded types when type is 'all' (the default). Previously notes ahead of a comment could push its permalink onto the wrong comment page. The get_page_of_comment_query_args filter receives a new type__not_in argument in that case.
  • get_lastcommentmodified() now stores its cached value with wp_cache_set_salted(). Code reading the lastcommentmodified:* keys from the timeinfo cache group directly should call the function instead.

See #65537.

AI Use

Claude Code drafted the code and this description, and I steered. I will review and test.

WP_Comment_Query hard-codes the exclusion of the 'note' comment type
(introduced in 6.9) with no extension point. Plugins that add their own
"private" comment types must instead rewrite query SQL through
comments_clauses in every context and re-verify it on each release.

Introduce a default_excluded_comment_types filter so extenders can
contribute additional comment types to the default-excluded set,
generalizing the existing 'note' handling. The default value of
array( 'note' ) preserves current behavior exactly.

See #65537.
@github-actions

github-actions Bot commented Jun 24, 2026 •

Copy link
Copy Markdown

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:

Props adamsilverstein, swissspidy, pfefferle, peterwilsoncc.

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


Props Bot commands

You can trigger Props Bot actions by commenting on this PR:

  • @propsbot add <username> to give props to a GitHub or WordPress.org user. Requires write access.
  • @propsbot remove <username> to leave a user out of the props. Requires write access.
  • @propsbot refresh to refresh this list. Adding the props-bot label works too.

@github-actions

Copy link
Copy Markdown

Hi there! 👋

Thank you for your contribution to WordPress! 💖

It looks like this is your first pull request to wordpress-develop. Here are a few things to be aware of that may help you out!

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,
The WordPress Project

@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.

Comment thread tests/phpunit/tests/comment/query.php Resolved
Comment thread tests/phpunit/tests/comment/query.php Resolved
…cess control.

The filter docblock described excluded types as "private", which could
be read as a security boundary. The exclusion only governs default
visibility; excluded types remain retrievable via explicit 'type' or
'all' requests, so document that callers must enforce capability checks
wherever comment data is displayed or exposed.
wp_update_comment_count_now() recalculated a post's stored comment_count
with a hard-coded 'AND comment_type != note', bypassing the
default_excluded_comment_types filter that hides those types from
WP_Comment_Query. A type that opted out of listings still inflated
comment_count and therefore get_comments_number().

Apply the same filtered exclusion set to the counter so the listings and
the stored count stay consistent, removing the need for plugins to also
re-implement the count via pre_wp_update_comment_count_now.

See #35214, #65537.
get_pending_comments_num() recomputed the admin pending-comments count with
a hard-coded 'AND comment_type != note', the same gap fixed in
wp_update_comment_count_now(): a type that opts out of default listings via
default_excluded_comment_types still inflated the pending bubble shown next
to each post in the admin list tables.

Derive the excluded set from the same filter so the pending count stays
consistent with the listings and the stored comment count.

See #35214, #65537.
adamsilverstein and others added 6 commits July 11, 2026 10:58
The default-excluded set plus filter application was triplicated across
WP_Comment_Query, wp_update_comment_count_now(), and
get_pending_comments_num(), each with subtly different normalization.
Centralize it in one accessor that all three call, which is also the
seam where a future comment type registry can derive the default from
internal types.

The accessor additionally strips the special type tokens understood by
WP_Comment_Query ('all', 'comment', 'comments', 'pings'): previously a
filter returning the 'pings' alias excluded nothing from the count
functions but zeroed out an explicit type => 'pingback' query, because
the explicit-request guard compares raw tokens while the query expansion
resolves aliases.

Also document the registration-timing contract (register the filter
unconditionally rather than toggling per call - the query cache key does
not include filter output), widen the null-context description, hoist
the invariant 'all' check out of the per-type loop, add the missing
@SInCE entry to wp_update_comment_count_now(), and make the
no-duplication test capture the WHERE clause via comments_clauses
instead of asserting against $wpdb->last_query.
…pes.

When default_excluded_comment_types excludes a literal ping type (for
example 'pingback'), a query requesting the 'pings' alias built
`comment_type IN ('pingback','trackback') AND comment_type NOT IN
('pingback')`, silently dropping the explicitly requested pingbacks. The
guard compared excluded literals against the raw request tokens, so an
alias never matched the literal it stands for.

Expand the request's special tokens ('comment', 'comments', 'pings') to
their literal comment_type values before deciding what to exclude, so a
type requested via an alias is honored. This also drops the redundant
NOT IN membership check, since the list is deduplicated with
array_unique() before the clause is built.
The normalization in wp_get_default_excluded_comment_types() ran the
filtered list through array_filter() with no callback, which drops the
string '0' along with empty strings. A comment type literally named '0'
could therefore never be excluded through the filter.

Filter on strlen() instead, so only empty strings are removed and '0'
survives as a valid literal type.
The default_excluded_comment_types docblock said the filter keeps types
out of listings, counts, "or feeds". Comment feeds are served by
WP_Query's raw SQL, which does not consult this filter, so the promise
does not hold. Describe only the surfaces the filter actually covers.
The list table hardcoded `type__not_in => array( 'note' )` for its row
query while the status count bubbles (via wp_count_comments()) now honor
default_excluded_comment_types. A plugin that removed 'note' from the
filter would therefore see the count include notes while the rows still
hid them, so "All (N)" disagreed with the visible list.

Source the row query's exclusions from wp_get_default_excluded_comment_types()
so the list and its counts stay in agreement.
Trunk's last-modified query hard-codes the 'note' and 'reaction'
exclusion, so a type added through the 'default_excluded_comment_types'
filter still moved the comment feed's Last-Modified date, and emptying
the filter did not bring notes back. Route it through
wp_get_excluded_comment_types_clause() like the feeds and counters.

The cached value keeps its fixed 'lastcommentmodified:<tz>' key, since
the comment status handlers clear it by that name. A changed excluded
set is therefore picked up the next time a comment changes status.

See #65537, #35214.
The docblocks and inline comments around the excluded comment types
had grown into design notes, some of them stale: the accessor and
filter docs still described 'note' as the only built-in default and
did not mention 'reaction' or get_lastcommentmodified(). Trim them to
what a caller needs and bring them in line with trunk.

Also drop the list table's 'comment'/'comments' alias branch, which
could never subtract anything because the accessor strips those
tokens, and filter the registry's internal type names to strings so
the merged default set is typed for array_unique().

See #65537, #35214.
New test methods and data providers need native types to pass PHPStan
at level 10.

See #65537.
Trunk is in the 7.2 beta, so these additions can no longer ship in 7.2.0.
…ed-comment-types-filter

# Conflicts:
#	src/wp-includes/class-wp-query.php
A hierarchical query caches the child IDs of each parent under a key built
from the query vars alone. The excluded set is not a query var and changing
it does not bump 'last_changed', so with a persistent object cache replies
of a newly excluded type kept rendering in threads, and replies of a type
that was no longer excluded stayed hidden.

The key now includes the set already resolved for the top-level query, the
same way the main query key does.

See #65537.
get_lastcommentmodified() reads the excluded comment types but cached its
result under a key that ignores them, and the cache is only cleared when a
comment changes status. After a plugin changed the set, comment feeds kept
sending a Last-Modified date taken from a comment they no longer list.

The value is now stored with wp_cache_set_salted(), salted with the set.
The key is unchanged, so the existing cache clearing still applies. Code
that reads the key directly now gets the salted array instead of a string.

See #65537.
The registry lookup was guarded by function_exists( 'get_comment_types' )
alone. Core does not define that function yet, so a plugin or theme
function of the same name would have been called, and whatever it returned
excluded from every comment query and count.

Also require the WP_Comment_Type class, which only the core registry
provides.

See #65537, #35214.
The filter passes the WP_Comment_Query instance, but the counts, the feeds
and get_lastcommentmodified() resolve the set with no query, and each level
of a threaded query resolves it with its own instance. A callback that
varies the set by query makes those disagree with the listed comments, so
say so in the filter documentation.

See #65537.
The list table expanded the 'pings' alias and subtracted the requested type
from the excluded set itself, repeating what WP_Comment_Query does for any
request other than 'all'. Only an 'all' request needs the exclusions passed
in, since the query drops its defaults for it.

See #65537.
The aliases 'all', 'comment', 'comments' and 'pings' are removed from the
filter output with an exact match, but the database compares comment_type
case-insensitively. A callback returning 'Comment' kept it in the set, and
the resulting NOT IN removed every regular comment from every query.

See #65537.
The list table refuses to filter by the note and reaction types, but it
compared the request exactly while the database matches comment_type in any
case and ignores trailing spaces. With those types removed from the
excluded set, ?comment_type=Note filtered the table to notes.

Normalize the request before the check, and pin that WP_Comment_Query only
lifts a default exclusion for an exact type name, which the REST and admin
note checks rely on.

See #65537.
@adamsilverstein

Copy link
Copy Markdown
Member Author

I ran another review pass over this one before asking for more eyes, and pushed the fixes that came out of it.

Claude did the review and the fixes, here is its rundown:

Six commits, 58c3d7c through c47ae92:

  • Descendants cache (58c3d7c) - fill_descendants() cached each parent's child IDs under a key built from the query vars alone. With a persistent object cache, replies of a newly excluded type kept rendering in threads. The key now includes the excluded set, same as the main query key.
  • get_lastcommentmodified() cache (41da618) - same class of problem: the cached date ignored the excluded set, so feeds could keep sending a Last-Modified taken from a comment they no longer list. The value is now stored with wp_cache_set_salted(), salted with the set. The key is unchanged so the existing cache clearing still applies, but anything reading lastcommentmodified:* from the cache directly now gets the salted array.
  • Registry guard (d783a42) - the internal-types lookup was guarded by function_exists( 'get_comment_types' ) only. Core doesn't define that function yet, so a plugin function of the same name would have been called and its return value excluded everywhere. It now also requires the WP_Comment_Type class from Comments: Introduce a register_comment_type() API #12311.
  • Aliases in any case (44d0973) - a callback returning 'Comment' or 'Pings' slipped past the alias strip, and since the database compares comment_type case-insensitively, the resulting NOT IN removed regular comments from every query.
  • List table (7429948, c47ae92) - dropped the duplicated alias expansion; the table now only passes the exclusions for an all request and leaves the rest to WP_Comment_Query. The note/reaction request guard also normalizes case and trailing spaces now, so ?comment_type=Note can't filter to notes when those types have been removed from the excluded set.
  • Docs (42db069) - the filter docblock now says that counts, feeds and get_lastcommentmodified() resolve the set without a query, so a callback that varies the set by $query makes them disagree with the listed comments.

One thing deliberately left strict: WP_Comment_Query only lifts a default exclusion for an exact type name. Matching the request case-insensitively looked like the obvious fix for an IN/NOT IN contradiction, but the REST and admin note checks compare the requested type exactly, so type=Note would have gone around them. There is a test pinning that now.

Not changed: the comment_feed_where fragment keeps the %i quoting requested earlier in review, even though it changes the string a callback might match on.

@peterwilsoncc whenever you have a chance, I'd still like your take on the 'all' vs '' approach from #12310 (comment) above - does that address your concern about themes that copied the default?

The accessor read the comment type registry behind class_exists() and
function_exists() guards, with a test that stays skipped until the
registry exists. Neither can be exercised on trunk, so reviewers would
be approving code that never runs.

Drop the branch and the skipped test. The registry change adds the
internal types through the filter instead, which needs no guard on
either side and works whichever lands first.

See #65537.
The counts, the feeds and get_lastcommentmodified() resolve the excluded
set without a query, and a threaded query resolves it once per level. A
callback that varied the set by query made those disagree with the
listed comments, and the docblock had to warn against using the
argument at all.

Drop the argument so the set is the same everywhere. A query that needs
other types still asks for them through 'type' or 'type__in'.

See #65537.
The normalization of the filter output was pinned one case per test, some
through a full query, and the false return was repeated for each caller
of the accessor. Cover it once with a data provider on the accessor.

Also drop tests that repeat a neighbour: the note default in the pending
count, the get_comment_link() pass-through, and the type__not_in
duplicate check that trunk already has for internal types.

See #65537.
@adamsilverstein adamsilverstein moved this from In Progress to Review in Comments First Class API (Trac #35214) Nov 19, 2026
…sor.

wp_get_excluded_comment_types_clause() declared its types while the
accessor it builds on did not, so callers got the list shape from the
docblock alone. Declare the array return and type the filter callback
that normalizes the set.

A filter that returns a non-array is still cast before it is returned,
so the declaration cannot raise a TypeError.

See #65537.
The new tests passed query results, cache reads and REST data straight
to helpers that expect a narrower type, which static analysis at the
strictest level reports and which would surface as a confusing error
rather than a failed assertion if a query returned something else.

Assert the type before using it, through a shared helper where the same
read was repeated, and declare the types of the filter callbacks.

See #65537.
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.

5 participants