Comments: Add filter for comment types excluded from queries by default - #12310
Comments: Add filter for comment types excluded from queries by default#12310adamsilverstein wants to merge 31 commits into
Conversation
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.
|
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 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. |
|
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. |
…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.
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.
There was a problem hiding this comment.
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_inis always set to the fullwp_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 (viaadmin_comment_types_dropdown), selecting that type will pass it viatypewhile also excluding it viatype__not_in, producing an empty result set (IN + NOT IN for the same type). This also breaks alias requests likecomment_type=pingswhenpingbackis 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,
| /** | ||
| * A filter callback returning a non-array degrades gracefully to no exclusions. | ||
| * | ||
| * @ticket 65537 | ||
| * @covers WP_Comment_Query::get_comment_ids | ||
| */ |
There was a problem hiding this comment.
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.
| 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 |
…ed-comment-types-filter
…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.
Description
WP_Comment_Queryexcludes thenotecomment 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: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_clausesin 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_typesfilter, read through awp_get_default_excluded_comment_types()accessor, that lets extenders contribute additional comment types to the default-excluded set: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 inWP_Query.Example usage:
Once the registry from #35214 lands, registering a type with
'internal' => trueis 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,noteis 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, andtests/phpunit/tests/rest-api/rest-comments-controller.php:note), and returning an empty list makesnoteappear again.type,type__in,type => 'all', or an alias (data providers).'0'preserved, special tokens stripped, no duplicate clause when the type is also intype__not_in.WP_Comment_Queryruns with the filter toggled in between return different results, and the filter runs once per query.wp_count_comments()does not include an excluded type.edit_postswho names it.noteand a filtered custom type) drop out ofget_page_of_comment(), an explicit'all'still counts them, andget_comment_link()no longer emits acpagethe comment is not rendered on.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
WP_Comment_Query,wp_update_comment_count_now(), andget_pending_comments_num()with subtly different normalizations, is now centralized in a newwp_get_default_excluded_comment_types()accessor.WP_Comment_Queryunderstands ('all','comment','comments','pings'). Previously a filter returning the'pings'alias excluded nothing from counts but zeroed out an explicittype => 'pingback'query.comments_clausesinstead of asserting against$wpdb->last_query.type__not_in. The exclusions are still forced there, sinceWP_Comment_Queryskips its own defaults for atype=allrequest, but the explicitly requested type is subtracted from the list first (with thecomment/comments/pingsaliases expanded) so a plugin that surfaces its excluded type viaadmin_comment_types_dropdowncan still list it.Later updates
WP_Querystill hard-codedcomment_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 preparedNOT INcondition 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.WP_Comment_Queryhashed only its query vars, salted with the commentlast_changedvalue. 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 bumpedlast_changed. The set is now resolved once inget_comments(), folded into the hashed args, and reused inget_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.get_comment_types( array( 'internal' => true ) )behind afunction_exists()guard, so registering a type as internal is enough once #12311 lands, and this PR can still land on its own.comment_countvalues and thecountscache group only refresh on comment writes.notetype 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.get_page_of_comment()counted older comments with'type' => 'all', the one value that makesWP_Comment_Queryskip its default exclusions, whilecomments_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 isWP_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 thenotetype - 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.