Skip to content

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

Open
tomjn wants to merge 2 commits into
Automattic:developfrom
tomjn:fix/902-pre-get-posts-early-return
Open

tomjn wants to merge 2 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

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.
@tomjn
tomjn requested a review from a team as a code owner October 2, 2026 15:20
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.
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.

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

1 participant