WordPress Alternating main loop (pre_get_posts filter) Targeting only main WordPress loop


Example

WordPress is applying pre_get_posts filter to literally any loop it generates. It means that all changes we are making in our callback function are applied to all exiting loops.

Obviously it is not what we want in most scenarios.

In most cases we would like to target only main loop, and only for non-admin screens.

We can use is_main_query() method and is_admin() global function to check if we are in the right place.

add_action( 'pre_get_posts', 'my_callback_function' );

function my_callback_function( $query ) {
    if( !$query->is_main_query() || is_admin() ) return;

    // this code will run only if
    // - this query is main query
    // - and this is not admin screen
}