Skip to content

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

Description

@tomjn

Bug Description

The PreGetPosts sniff warns when a pre_get_posts callback changes the query without checking is_main_query() first. A callback that returns early for every other query has made that check, so it should not get the warning.

It does get the warning when the early return is not the first statement inside the if. Logging a message before returning is enough to cause it.

Expected: no warning for the snippet below.

Actual: a warning on the $query->set() line. Remove the do_log() line and the warning goes away.

The cause is in PreGetPostsSniff::isEarlyMainQueryCheck(). It looks for the return with findNext() in local mode, which stops at the first statement terminator, so only the first statement in the if body is searched.

@GaryJones found this while reviewing #901.

Minimal Code Snippet

add_action( 'pre_get_posts', function( $query ) {
	if ( ! $query->is_main_query() ) {
		do_log( 'x' );
		return;
	}
	$query->set( 'cat', '-5' );
} );

Error Code

WordPressVIPMinimum.Hooks.PreGetPosts.PreGetPosts

Main WP_Query is being modified without $query->is_main_query() check. Needs manual inspection.

Environment

Question Answer
PHP version 8.5.11
PHP_CodeSniffer version 3.13.6
PHPCSUtils version 1.2.3
VIPCS version main at 9c47cd0 (3.1.0) and develop at bdd2160
WordPressCS version 3.4.1
PHPCSExtra version 1.5.1
VariableAnalysis version 2.13.0

Tested Against main branch?

  • I have verified the issue still exists in the main branch of VIPCS.
  • I have verified the issue still exists in the develop branch of VIPCS.

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions