What is the pre_get_posts hook?

pre_get_posts gives you the WP_Query object before the database is asked. You can change its arguments with $query->set(). Always check that it is the main query, and not in the admin, or you will change other queries by mistake.

<?php
add_action( 'pre_get_posts', function ( $query ) {
	if ( ! is_admin() && $query->is_main_query() && $query->is_home() ) {
		$query->set( 'posts_per_page', 2 );
	}
} );
Terminal output

$ curl -s http://example.com/ | grep -o 'target="_self" >[^<]*' | sed 's/.*>//'
Post C
Post B

The home page lists only two posts now (without the hook it shows ten). Use it also for custom post types in archives, search results or to change the order.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.