WordPressAlternating main loop (pre_get_posts filter)


Syntax

  • add_action( 'pre_get_posts', 'callback_function_name' );
  • function callback_function_name( $query ) {}
  • // for PHP 5.3.0 or above
  • add_action( 'pre_get_posts', function( $query ){} );

Parameters

ParameterDetails
$query(WP_Query) Loop object

Remarks

If you are using PHP 5.3.0 or above, you can use closures (anonymous functions)

add_action( 'pre_get_posts', 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
});