Skip to content

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

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

Comments: Add filter for comment types excluded from queries by default#12310
adamsilverstein wants to merge 31 commits into
WordPress:trunkfrom
adamsilverstein:feature/65537-excluded-comment-types-filter

Conversation

@adamsilverstein

@adamsilverstein adamsilverstein commented Jun 24, 2026

Copy link
Copy Markdown
Member

Description

WP_Comment_Query excludes the note comment type (introduced in 6.9 for the editor Notes feature) from results by default, but the exclusion list is hard-coded with no extension point:

if (
    ! in_array( 'all', $raw_types['IN'], true ) &&
    ! in_array( 'note', $raw_types['IN'], true ) &&
    ! in_array( 'note', $raw_types['NOT IN'], true )
) {
    $raw_types['NOT IN'][] = 'note';
}

A plugin that introduces its own "private" comment type (one that should never appear in standard comment listings, counts, or feeds) has to rewrite the SQL through comments_clauses in every context and re-verify that work on each release. This is the "whack-a-mole" problem reported by the Alpaca issue-tracker plugin, which maintains a dedicated library to do exactly this.

Approach

Introduce a default_excluded_comment_types filter, read through a wp_get_default_excluded_comment_types() accessor, that lets extenders contribute additional comment types to the default-excluded set:

function wp_get_default_excluded_comment_types( $query = null ) {
    $default_excluded_types = array( 'note' );

    if ( function_exists( 'get_comment_types' ) ) {
        $default_excluded_types = array_values(
            array_unique(
                array_merge(
                    $default_excluded_types,
                    get_comment_types( array( 'internal' => true ), 'names' )
                )
            )
        );
    }

    $excluded_types = apply_filters( 'default_excluded_comment_types', $default_excluded_types, $query );

    // ... normalization ...
}

Every consumer reads the same set: WP_Comment_Query, wp_update_comment_count_now(), get_pending_comments_num(), the comments list table, and the three comment feed queries in WP_Query.

Example usage:

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

Once the registry from #35214 lands, registering a type with 'internal' => true is enough and the filter is left for exceptions.

Scope / non-goals

This is deliberately a small step, not the full custom-comment-types API tracked in #35214. It adds no registration object, labels, capabilities, or admin UI. It only generalizes the existing default-exclusion behavior so private types can opt in without rewriting query SQL.

Backward compatibility

Without the registry, the default set is array( 'note' ), which preserves current behavior exactly. With the registry, note is the only internal built-in, so the set is unchanged there too. No change for sites that don't use the filter.

Testing

Coverage lives in tests/phpunit/tests/comment/query.php, tests/phpunit/tests/query/commentFeed.php, tests/phpunit/tests/admin/wpCommentsListTable.php, tests/phpunit/tests/admin/includes/comment/GetPendingCommentsNum_Test.php, tests/phpunit/tests/comment/wpUpdateCommentCountNow.php, and tests/phpunit/tests/rest-api/rest-comments-controller.php:

  • A custom type added via the filter is excluded by default (alongside note), and returning an empty list makes note appear again.
  • An excluded type is still returned when explicitly requested via type, type__in, type => 'all', or an alias (data providers).
  • Normalization: non-scalar values dropped, '0' preserved, special tokens stripped, no duplicate clause when the type is also in type__not_in.
  • Feeds: the site-wide, archive, and single-post comment feeds all drop an excluded type, and pick up a change to the excluded set rather than serving a stale cache entry.
  • Caching: two identical WP_Comment_Query runs with the filter toggled in between return different results, and the filter runs once per query.
  • Counts: wp_count_comments() does not include an excluded type.
  • REST: an excluded type stays out of the default collection, cannot be enumerated by an unauthenticated caller, is still readable by ID, and is still returned to a caller with edit_posts who names it.
  • Pagination: excluded types (both note and a filtered custom type) drop out of get_page_of_comment(), an explicit 'all' still counts them, and get_comment_link() no longer emits a cpage the comment is not rendered on.
$ phpunit --filter 'Tests_Comment|Tests_Feed|Tests_Query|GetPendingCommentsNum|wpCommentsListTable|REST_Comments'
OK (1545 tests, 5504 assertions)

One test is skipped until register_comment_type() lands, since it needs the registry to assert that an internal type is excluded without touching the filter.

Review updates

  • The default set + filter application, previously triplicated across WP_Comment_Query, wp_update_comment_count_now(), and get_pending_comments_num() with subtly different normalizations, is now centralized in a new wp_get_default_excluded_comment_types() accessor.
  • The accessor strips the special type tokens WP_Comment_Query understands ('all', 'comment', 'comments', 'pings'). Previously a filter returning the 'pings' alias excluded nothing from counts but zeroed out an explicit type => 'pingback' query.
  • Tests were added for non-array filter returns at all three call sites and for alias stripping; the no-duplication test now captures the WHERE clause via comments_clauses instead of asserting against $wpdb->last_query.
  • The comments list table no longer passes the full excluded set through type__not_in. The exclusions are still forced there, since WP_Comment_Query skips its own defaults for a type=all request, but the explicitly requested type is subtracted from the list first (with the comment/comments/pings aliases expanded) so a plugin that surfaces its excluded type via admin_comment_types_dropdown can still list it.

Later updates

  • Comment feeds. The three feed WHERE clauses in WP_Query still hard-coded comment_type != 'note', so a filtered private type was served in /comments/feed/, archive comment feeds, and per-post comment feeds - unauthenticated public output, which defeats the point of excluding it. All three now build a prepared NOT IN condition from the same filtered set, through a private _wp_get_excluded_comment_types_clause() helper that the comment counter and the pending count share too. Both feed paths key their caches on the query string, so the new condition is part of the key already.
  • Query cache key. WP_Comment_Query hashed only its query vars, salted with the comment last_changed value. The excluded set is neither, so with a persistent object cache, activating a plugin left previously cached ID lists in place - still containing the type that is now excluded - until an unrelated comment write bumped last_changed. The set is now resolved once in get_comments(), folded into the hashed args, and reused in get_comment_ids(), so the filter still runs once per query. That also means the docblock's registration-timing note is a caching best practice now rather than a correctness contract.
  • Registry wiring. The accessor seeds its default from get_comment_types( array( 'internal' => true ) ) behind a function_exists() guard, so registering a type as internal is enough once #12311 lands, and this PR can still land on its own.
  • Recount guidance. The filter docblock now says that a plugin excluding a type with comments already in the database has to recount the affected posts on activation and deactivation, since stored comment_count values and the counts cache group only refresh on comment writes.
  • Visibility boundaries. Two surfaces sit next to the exclusion set without being driven by it, and neither said so. The list table drops a request for the note type independently of the filter, so emptying the excluded set surfaces notes in the untyped views while still refusing to filter the table to them - deliberate, since notes carry their own visibility rules. Over REST, excluding a type only changes the default collection. Both are now stated in the code and pinned with tests.
  • Comment page math. get_page_of_comment() counted older comments with 'type' => 'all', the one value that makes WP_Comment_Query skip its default exclusions, while comments_template() renders the same post with them applied. Two notes ahead of a comment on a two-per-page post were enough to send its #comment- permalink to page 2 while the comment renders on page 1. The default is now '', which is WP_Comment_Query's own default and counts exactly what the list shows; passing 'all' explicitly still counts everything. get_comment_link() forwards its arguments here and carried the same default, so it moves too. This one predates the filter - it has been reachable since 6.9 gave core the note type - but the filter generalizes it to any private type a plugin registers.

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

AI Use

Both the code and this description were written with Claude, working from a review of the PR. 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. 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 adamsilverstein, swissspidy.

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

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 src/wp-includes/class-wp-comment-query.php Outdated
Comment thread src/wp-includes/class-wp-comment-query.php Outdated
Comment thread tests/phpunit/tests/comment/query.php Outdated
Comment thread tests/phpunit/tests/comment/query.php Outdated
…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.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated no new comments.

Comments suppressed due to low confidence (1)

src/wp-admin/includes/class-wp-comments-list-table.php:160

  • type__not_in is always set to the full wp_get_default_excluded_comment_types() list. If a plugin adds a custom type to that list and also exposes it in the comment type dropdown (via admin_comment_types_dropdown), selecting that type will pass it via type while also excluding it via type__not_in, producing an empty result set (IN + NOT IN for the same type). This also breaks alias requests like comment_type=pings when pingback is excluded by default.

Consider removing explicitly requested types from type__not_in (including expanding the pings alias to pingback/trackback) so the list table can still show an excluded type when it is explicitly selected.

			'post_id'                   => $post_id,
			'type'                      => $comment_type,
			'type__not_in'              => wp_get_default_excluded_comment_types(),
			'orderby'                   => $orderby,
			'order'                     => $order,

Copilot AI review requested due to automatic review settings July 24, 2026 03:27

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated no new comments.

Copilot AI review requested due to automatic review settings July 24, 2026 16:40

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated no new comments.

Copilot AI review requested due to automatic review settings July 25, 2026 15:55

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated 3 comments.

Comment thread tests/phpunit/tests/comment/wpUpdateCommentCountNow.php
Comment on lines +5758 to +5763
/**
* A filter callback returning a non-array degrades gracefully to no exclusions.
*
* @ticket 65537
* @covers WP_Comment_Query::get_comment_ids
*/

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Agreed, same wording problem here. The docblock now says a false return degrades to no exclusions and notes that a scalar return is cast and treated as a single excluded type, and the test is renamed to test_default_excluded_comment_types_filter_false_return_is_tolerated. Fixed in e0e1c5e.

The comments list table passed the full default-excluded set as
'type__not_in', which contradicts an explicit 'type' request for one of
those types and returns an empty list. A plugin that adds its own private
type to the excluded set and surfaces it through
'admin_comment_types_dropdown' could therefore never list it.

The requested type is now removed from 'type__not_in' before the query
runs, with the 'comment'/'comments'/'pings' aliases expanded the same way
WP_Comment_Query expands them. The exclusions are still forced for
unrequested types so that a 'type=all' request, which makes
WP_Comment_Query skip its own default exclusions, does not surface them
in the list table.

Also narrows the "non-array filter return" test docblocks: only values
that normalize to an empty set disable the exclusions, since the accessor
casts a scalar return to an array and treats it as a single excluded type.
Copilot AI review requested due to automatic review settings July 25, 2026 22:21

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 8 out of 8 changed files in this pull request and generated 1 comment.

Comment thread src/wp-admin/includes/class-wp-comments-list-table.php Outdated
Copilot AI review requested due to automatic review settings July 26, 2026 00:10

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 8 out of 8 changed files in this pull request and generated 1 comment.

Comment on lines +2891 to +2896
function wp_get_default_excluded_comment_types( $query = null ) {
/**
* Filters the comment types that are excluded from query results by default.
*
* Comment types in this list are omitted from `WP_Comment_Query` results
* unless the query explicitly requests the 'all' type, or explicitly
…he key.

WP_Comment_Query hashes its query vars and salts the key with the comment
`last_changed` value. The default-excluded types are neither: they are resolved
from a filter on every cache miss, so the SQL they produce was never reflected
in the key. With a persistent object cache, activating a plugin that excludes a
type left previously cached ID lists in place, still containing that type, until
some unrelated comment write bumped `last_changed` - potentially indefinitely on
a quiet site. Deactivating had the mirror problem, hiding types that should have
come back.

Resolve the excluded set once in get_comments(), fold it into the hashed args,
and reuse it in get_comment_ids() so the filter still runs only once per query.
Each distinct set now gets its own cache entry, which also makes per-call
toggling safe rather than merely discouraged.

See #65537.
… feeds.

The comment feed queries in WP_Query are assembled directly rather than through
WP_Comment_Query, and still hard-coded `comment_type != 'note'` in all three of
their WHERE clauses. A plugin that used `default_excluded_comment_types` to keep
a private type out of comment listings therefore still had that type served in
the site-wide, archive, and per-post comment feeds - unauthenticated public
output, which defeats the point of excluding it.

Route the three clauses through the same filtered set. The excluded types are
compiled into a prepared `NOT IN` condition by a new private helper, which the
comment counter and the pending-comment count now share too, so the four
directly-assembled queries can no longer drift apart. The helper emits nothing
when the set is empty. Both feed paths key their caches on the query string, so
the new condition is part of the key already.

See #65537.
…al types.

Keeping a comment type out of the default listings took two separate steps once
the registry landed: registering the type with `'internal' => true`, then adding
the same name through `default_excluded_comment_types`. Two mechanisms for one
intent invites plugins to do only one of them - skipping registration leaves the
type without labels, REST discovery, or rendering, while skipping the filter
leaves it visible despite being declared internal.

Seed the default set from `get_comment_types( array( 'internal' => true ) )`, so
declaring a type internal is enough and the filter is left for exceptions. The
registry is not a hard dependency: the lookup is guarded by function_exists() so
this can land before register_comment_type() does, and 'note' stays in the set
unconditionally so the default also holds before types are registered on 'init'.

The accompanying test skips until the registry is available.

See #65537, #35214.
Two places sit next to the new exclusion set without being driven by it, and
neither said so. The comments list table drops a request for the note type
independently of the filter, so emptying the excluded set surfaces notes in the
untyped views while still refusing to filter the table to them; that asymmetry
is deliberate, since notes carry their own visibility rules, but the old comment
claimed notes are simply never listed. Over REST, excluding a type changes only
the default collection: the type stays readable by ID and is still returned to a
caller with edit_posts who names it, which is the documented "visibility, not
access control" contract.

Say both out loud in the code and pin them with tests, so a later change to
either surface has to be a decision rather than an accident. Also note that the
list table's comment/comments alias branch cannot subtract anything, since the
accessor strips those tokens from the excluded set.

See #65537.
array_filter() with 'strlen' was doing the right thing at runtime - dropping ''
while keeping a type literally named '0' - but strlen() returns an int, not a
bool, so PHPStan reports the callback as the wrong type and the static analysis
job fails. Say what the filter means instead.

See #65537.
…ath.

get_page_of_comment() counted older comments with 'type' => 'all', which is the
one value that makes WP_Comment_Query skip its default exclusions, while
comments_template() renders the same post with those exclusions applied. Every
excluded-type comment older than the target therefore inflated the count, so a
'#comment-' permalink could point at a page the visitor never sees. Two notes
ahead of a comment on a two-per-page post were enough to send its permalink to
page 2 while the comment renders on page 1.

Default the argument to '' instead, which is WP_Comment_Query's own default and
so counts exactly what the comment list shows. Callers wanting the old behavior
can still pass 'all' explicitly. get_comment_link() forwards its arguments here
and carried the same default, so it moves too, otherwise the fix would never
reach the permalinks that need it.

This predates the exclusion filter - it has been reachable since 6.9 gave core
the note type - but the filter generalizes it to any private type a plugin
registers.

See #65537.
The branch was written while trunk was 7.1-alpha; trunk is now
7.2-alpha, so the eleven @SInCE tags this branch adds pointed at a
release that will never contain them. Docblock-only change.

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.

3 participants