How To Modify WordPress Main Query

0
21
views



Are you looking for changing the WordPress Main Query without changing the core files of WordPress? Then yes, It is possible to do modification in the WordPress Main Query using WordPress Hooks. Today I will be explained about it.

Blog site’s home page is showing maximum 10 numbers of the blog in default settings with descending order. Suppose you want to change the home page query then it would be possible to change it but it has some limitation.

When I have started WordPress, Even now, We developers are changing the WordPress theme pages. We are going to make changes in the theme loop. It’s usually done by adding a call to the function query_posts and a few arguments above the while loop. This is quite simple tricks to the modification with a couple of problems like below.

  1. After changed, it does not support pagination.
  2. You have to edit each template where while loop is used in the theme.

If you agreed on this changes and moved to the next things but we are not sure that our changes will be kept forever because our changes will be lost after updating the theme. So better solution is  Modify WordPress Main Query.

WordPress pre_get_posts Hooks

pre_get_posts is a WordPress action hook and you can modify the main query anywhere on your site without ever touching a theme’s files and the pagination will work continue. pre_get_posts is a WordPress action hook that is called after the query variable, but before the actual query is run. This means your changes are direct to the object itself and not during run time which offers a lot more control and flexibility.

 



 

Here is the simple code.

In the above example, you can modify your changes as per your requirement. I hope you have got the idea  How To Modify WordPress Main Query. If you have any queries or questions, Please write it in the below comment form or if you want to implement on your site then please contact us.

 



LEAVE A REPLY

4 × 2 =