WordPress Alternating main loop (pre_get_posts filter) Pre get posts filter basic usage


Example

Sometimes you would like to change main WordPress query.

Filter pre_get_posts is the way to go.

For example using pre_get_posts you can tell main loop to show only 5 posts. Or to show posts only from one category, or excluding any category etc.

add_action( 'pre_get_posts', 'my_callback_function' );

function my_callback_function( $query ) {
    // here goes logic of your filter
}

As you can see, we are passing main loop query object into our callback function argument.

Important note here: we are passing argument as a reference. It means that we do not need to return query or set any globals to get it working. As $query is a reference to the main query object, all changes we make on our object are immediately reflected in the main loop object.