Skip to content

Recognise is_main_query() checks in an elseif in PreGetPosts - #906

Merged
GaryJones merged 1 commit into
developfrom
GaryJones/pre-get-posts-elseif
Oct 10, 2026
Merged

GaryJones merged 1 commit into
developfrom
GaryJones/pre-get-posts-elseif

Conversation

@GaryJones

Copy link
Copy Markdown
Contributor

The PreGetPosts sniff only recognised an is_main_query() check when it was in an if. The same check in an elseif was ignored, which gave two false positives.

An early return in an elseif was not seen as an early return, so the code after it was flagged:

add_action( 'pre_get_posts', function( $query ) {
	if ( is_admin() ) {
		return;
	} elseif ( ! $query->is_main_query() ) {
		return;
	}
	$query->set( 'cat', '-5' ); // Was flagged.
} );

A set() inside an elseif that checks the main query was flagged as well. This is a common pattern when home and search are adjusted in separate branches:

add_action( 'pre_get_posts', function( $query ) {
	if ( $query->is_main_query() && $query->is_home() ) {
		$query->set( 'cat', '-5' );
	} elseif ( $query->is_main_query() && $query->is_search() ) {
		$query->set( 'cat', '-6' ); // Was flagged.
	}
} );

The three checks that look for the surrounding if now accept an elseif too. An elseif that does not check the main query is still flagged, and there is a test for that. else if, written as two words, already worked because PHP_CodeSniffer tokenises it as an else followed by an if. It now has a test so it stays that way.

One related case is left as it is. A set() in the else of if ( ! $query->is_main_query() ) is still flagged, because accepting it would mean the sniff has to understand the negation.

This came up while reviewing #904.

The sniff only recognised an is_main_query() check in an if, so two
common patterns were flagged. An early return under an elseif that
checks the main query was missed, and so was a set() inside an elseif
whose condition checks it, as when home and search are tweaked in
separate branches.
@GaryJones
GaryJones requested a review from a team as a code owner October 9, 2026 21:43
@GaryJones GaryJones added this to the 3.x milestone Oct 9, 2026
@GaryJones GaryJones self-assigned this Oct 9, 2026
@GaryJones
GaryJones merged commit 32c6b14 into develop Oct 10, 2026
26 checks passed
@GaryJones
GaryJones deleted the GaryJones/pre-get-posts-elseif branch October 10, 2026 16:14
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.

1 participant