Skip to content

Don't flag pre_get_posts callbacks whose early return follows another statement - #904

Merged
GaryJones merged 3 commits into
Automattic:developfrom
tomjn:fix/902-pre-get-posts-early-return
Oct 9, 2026
Merged

GaryJones merged 3 commits into
Automattic:developfrom
tomjn:fix/902-pre-get-posts-early-return

Conversation

@tomjn

@tomjn tomjn commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

A pre_get_posts callback that returns early for anything other than the main query was still flagged if the return was not the first statement in the if, for example when it logged something first.

The sniff now accepts a return anywhere in the if, as long as it belongs to the if itself.

That last part changes behaviour in one direction worth knowing about. A return inside a nested condition or a nested closure no longer counts as an early exit, so the code below it is flagged. The old search accepted those when they came first in the if, but they do not stop other queries from reaching the code below.

This touches the same lines as #901, so whichever merges second will need a small conflict fix.

Fixes #902

@tomjn
tomjn requested a review from a team as a code owner October 2, 2026 15:20
tomjn and others added 3 commits October 9, 2026 22:05
The search for the return ran in local mode, which stops at the first statement terminator, so a return after any other statement was missed and the rest of the callback was flagged.

It now accepts a return that belongs to the if itself. A return inside a nested condition or closure no longer counts, because it does not stop the other queries from reaching the code below. The old search accepted those when they came first.
PHPStan is configured to analyse as PHP 7.1, where array_key_last() does not exist. Use the array_keys() and array_pop() pattern the sniff already uses elsewhere.
The old search for the early return also missed it in an if written
with alternative syntax, when the return was not the first statement.
The new search finds it there too, so this pins that down.
@GaryJones
GaryJones force-pushed the fix/902-pre-get-posts-early-return branch from 120f759 to 1e3d29e Compare October 9, 2026 21:07
@GaryJones GaryJones self-assigned this Oct 9, 2026
@GaryJones GaryJones added this to the 3.x milestone Oct 9, 2026
@GaryJones
GaryJones merged commit 6c0573e into Automattic:develop Oct 9, 2026
20 checks passed
@GaryJones

Copy link
Copy Markdown
Contributor

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: PreGetPosts warns when the early is_main_query() return is not the first statement in its if

2 participants