Skip to content

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

Open
adamsilverstein wants to merge 23 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 23 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 that lets extenders contribute additional comment types to the default-excluded set, generalizing the existing hard-coded note handling:

$excluded_types = apply_filters_ref_array( 'default_excluded_comment_types', array( array( 'note' ), &$this ) );

foreach ( array_unique( (array) $excluded_types ) as $excluded_type ) {
    if (
        ! in_array( 'all', $raw_types['IN'], true ) &&
        ! in_array( $excluded_type, $raw_types['IN'], true ) &&
        ! in_array( $excluded_type, $raw_types['NOT IN'], true )
    ) {
        $raw_types['NOT IN'][] = $excluded_type;
    }
}

Because WP_Comment_Query backs the majority of comment outputs (admin list table, get_comments(), REST collection queries, feeds), a single registration point here removes most of the per-context filtering a plugin currently needs.

Example usage:

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

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

The default value array( 'note' ) preserves current behavior exactly. No change for sites that don't use the filter.

Testing

Adds full coverage to tests/phpunit/tests/comment/query.php:

  • A custom type added via the filter is excluded by default (alongside note).
  • Returning an empty list makes note appear again, proving the default is filterable.
  • An excluded type is still returned when explicitly requested via type, type__in, or type => 'all' (data provider).
  • The filter receives the default array( 'note' ) and the WP_Comment_Query instance.
  • A filtered type is added to the query SQL only once when also passed in type__not_in.
$ phpunit tests/phpunit/tests/comment/query.php
OK (164 tests, 482 assertions)

$ phpunit --group comment
OK (555 tests, 1381 assertions)

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 is also the seam where a future comment type registry can derive the default from internal types.
  • 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.
  • The canonical filter docblock moved to the accessor and now documents the registration-timing contract - register the filter unconditionally on plugins_loaded/init, do not toggle it per call, since the query cache key does not include the filter output - and that returned values must be literal comment_type values.
  • 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.

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

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.
Casting the filter output with array_map( 'strval', ... ) trusts every
callback to return strings. A callback that returns an object without
__toString() raises an Error, and one that returns a nested array emits
an "Array to string conversion" warning and silently adds the literal
string "Array" to the exclusion list.

Filter the raw output through is_scalar() before casting, so unusable
values are discarded rather than fataling or poisoning the list. This
matches how wp_speculation_rules_href_exclude_paths is normalized in
speculative-loading.php and how wp_parse_list() guards its own input.

Scalar values keep their existing treatment, including the '0' comment
type, so no currently valid filter return changes behavior.

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 1 comment.

Comment thread src/wp-includes/comment.php Outdated
Copilot AI review requested due to automatic review settings July 24, 2026 00:26

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 1 comment.

Comment on lines 156 to 160
'post_id' => $post_id,
'type' => $comment_type,
'type__not_in' => array( 'note' ),
'type__not_in' => wp_get_default_excluded_comment_types(),
'orderby' => $orderby,
'order' => $order,

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.

Good catch, fixed in e0e1c5e.

I didn't drop type__not_in entirely though - the list table still has to force the exclusions for a type=all request. WP_Comment_Query skips its default exclusions when 'all' is requested, and there is an existing test (test_comments_list_table_does_not_show_note_comment_type, added for #64198/#64474) asserting notes stay hidden on edit-comments.php?comment_type=all. Removing the arg outright regresses that.

Instead the requested type is now subtracted from the exclusion list before the query runs, with the 'comment'/'comments'/'pings' aliases expanded the same way WP_Comment_Query expands them:

$excluded_types = array_values( array_diff( wp_get_default_excluded_comment_types(), $requested_types ) );

The 'note' type is still stripped from the request a few lines above, so that one remains unlistable in the admin regardless.

Added two tests in tests/phpunit/tests/admin/wpCommentsListTable.php: a filtered-in 'private' type stays hidden for both an empty and an all request, and it is listed when explicitly selected. The second one fails against the old code (0 items) and passes now.

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Copilot AI review requested due to automatic review settings July 24, 2026 02:57

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