Customizing the Default Query
Explore how to customize the default WordPress query by using the pre_get_posts action hook. Understand how to modify queries on specific archive pages to order posts by custom fields and filter out past events. This lesson helps you enhance WordPress data display while improving performance by altering the existing query instead of adding a custom one.
By default query, we mean the query WordPress runs based on the URL or slug of the page. If we are visiting the blogs archive page, /blogs, WordPress knows it has to query for the blog posts. On the archive page for custom post type events, /events, WordPress automatically queries all the events.
To show event posts on the homepage, we used a custom query to order the posts according to the event date while filtering out events from the past. For the event archive page, we want a similar query which lists all upcoming events. Right now the events archive page lists all the events according to the date the event post was created.
While we can copy the custom query code from front-page.php to archive-events.php, we do not need a custom query when the default query for /events can be tweaked. On the homepage, we needed the custom query because WordPress was not going to query for events posts by default. Here, the default query is already fetching the most recent event posts.
Displaying posts on the event archive page
Open archive-events.php. The code from the while loop is reproduced ...