WordPress Alternating main loop (pre_get_posts filter)

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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
});


Got any WordPress Question?