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.
WordPress snippets using the pre_get_posts hook
-
How to Restrict Users to View Only Media Library Items They Upload in WordPress
-
How to Display Recent Drafts from All Authors in WordPress
-
How to Display All the Posts from This Month in WordPress
-
How to Order Categories by Most Recently Updated in WordPress
-
How to Only Show the Author’s Posts in the WordPress Edit List
-
How to Limit Search Results to Specific Post Types in WordPress
-
How to Include Future Posts in Your WordPress RSS Feed
-
How to Include All Post Types in WordPress Search Results
-
How to Ignore Sticky Posts in WordPress: A Simple Guide