pre_get_posts

Home » Hooks » pre_get_posts

The pre_get_posts hook is a powerful WordPress hook that allows you to modify and control the query before it’s executed. It’s used to customize the main query of the current page or post, and to alter the parameters of the query to display different kinds of content.

This hook is particularly useful for developers who want to change the behavior of the main query, for example, to display custom posts or to exclude specific ones. It can also be used to change the order of posts, the number of posts displayed on a page, and the category or tag of the posts.

The pre_get_posts hooks accepts one argument, which is an instance of the WP_Query class. This class represents the current query and contains all the parameters that define the query.

Here’s an example usage code of the pre_get_posts hook:

function my_custom_query( $query ) {
   if ( !is_admin() && $query->is_main_query() && $query->is_home() ) {
      $query->set( 'post_type', array( 'post', 'page', 'my_custom_post_type' ) );
   }
}
add_action( 'pre_get_posts', 'my_custom_query' );

In this example, we’re using the pre_get_posts hook to modify the main query of the home page. We’re checking if we’re not in the admin area, if it’s the main query, and if it’s the home page. If all these conditions are met, we’re setting the post type parameter to include posts, pages, and our custom post type called "my_custom_post_type". This will modify the query to display all these post types on the homepage.

Overall, the pre_get_posts hook is a powerful tool for customizing the WordPress query, and it can be used in many different ways to achieve a variety of results.

Learn More on WordPress.org

Register an account to save your snippets or go Pro to get more features.