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?
Bug Description
The
PreGetPostssniff warns when apre_get_postscallback changes the query without checkingis_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
returnis not the first statement inside theif. 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 thedo_log()line and the warning goes away.The cause is in
PreGetPostsSniff::isEarlyMainQueryCheck(). It looks for thereturnwithfindNext()in local mode, which stops at the first statement terminator, so only the first statement in theifbody is searched.@GaryJones found this while reviewing #901.
Minimal Code Snippet
Error Code
WordPressVIPMinimum.Hooks.PreGetPosts.PreGetPostsEnvironment
mainat 9c47cd0 (3.1.0) anddevelopat bdd2160Tested Against
mainbranch?mainbranch of VIPCS.developbranch of VIPCS.