Sometimes you find yourself the need to limit the query's in an attempt to speed up your site as WordPress will do a query of posts it is to display before hitting any theme files or plugins by default.  According to the WordPress Codex for pre_get_posts defines it as:

This hook is called after the query variable object is created, but before the actual query is run.

The pre_get_posts action gives developers access to the $query object by reference (any changes you make to $query are made directly to the original object – no return value is necessary).

 Using this action in your functions or a plugin will allow you to manipulate the query before it happens allowing you to only query the database once for what is going to be displayed.  So say you would like to limit the posts that are being shown on the home page.  Using the is_home() conditional call would allow you to then customize the query to only display from a certain category or if it has a specific tag.

[snippet id=”46″]

If you happen to have a recent posts widget in your sidebar unfortunately this also changes the query for this section too so if there is a section on your website that uses all of your posts or needs to be able to reference more than what you want the main display to be limited too you should think about creating a separate query still.

So in my instance since I am showing the latest 5 posts I could limit the initial query to 5 in the filter as I want to display the latest 5 from everyone and then just do another query for me as the author to speed up my site.

So if you do not need to load all of the posts it would normally do then utilizing this action will allow you to make the query to the database faster and quicker due to not having to load unnecessary data.

Share This

We are using cookies on our website

Please confirm, if you accept our tracking cookies. You can also decline the tracking, so you can continue to visit our website without any data sent to third party services.