WordPress pre_get_posts hook allows us to change the query parameter of WP_Query before starting query posts. In this tutorial, we will introduce how to use it.
How to use pre_get_posts?
You can use this hook as follows:
add_action( 'pre_get_posts', 'pre_get_posts_function' );
You should implement pre_get_posts_function by your own.
How to implement pre_get_posts_function?
Here is an example:
function pre_get_posts_function( $query ){ $query->set( 'post_type', array( 'post', 'course' ) ); return $query; }
This function will receive a $query parameter, which contains the sql condition that will be used in WP_Query.
We can use $query->set() function to change the query condition of WP_Query. In order to set query parameters correctly, you should know what query parameters will be used in WP_Query. Here is an tutorial:
A Full List of WordPress WP_Query Query Arguments ($args) – WordPress Tutorial
As to example code above, we will set post_type query parameter to “post” and “course“, which means we will query two types of posts.
We also can set different query parameters by conditions, here is an example:
function pre_get_posts_function( $query ){ if (is_admin() || !$query->is_main_query()){ return; } if ($query->is_search() ) { $query->set('posts_per_page', 30); } if($query->is_main_query() && !is_admin() && $query->is_home()) { $query->set( 'cat', '-4' ); } return $query; }
We can use $query->is_function() to check different conditions.