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 23 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.
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.
| '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, |
There was a problem hiding this comment.
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>
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 |
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 that lets extenders contribute additional comment types to the default-excluded set, generalizing the existing hard-codednotehandling:Because
WP_Comment_Querybacks 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:
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:note).noteappear again, proving the default is filterable.type,type__in, ortype => 'all'(data provider).array( 'note' )and theWP_Comment_Queryinstance.type__not_in.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. The accessor is also the seam where a future comment type registry can derive the default from internal types.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.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 literalcomment_typevalues.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.Trac ticket: https://core.trac.wordpress.org/ticket/65537