How to choose between hooking into per_get_posts or into parse_query

In refactoring my code base I noticed there are two hooks that used for modifying the main query.

  • parse_query
  • pre_get_posts

From the Plugin API Reference it seems these hooks fire back to back and both have access to the main WP_Query object. I need to know how they are different in order to determine which one is the proper choice for my needs. The developer docs for parse_query and pre_get_posts don’t provide sufficient information to answer this question.

The code that uses parse_query is based on an article on filtering admin listings based on a custom fields.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I’m looking real hard at the code around both hooks, and they run one right after the other, with the same arguments, and I just can’t see any meaningful difference.

Theoretically only parse_query would run, and not pre_get_posts, if WP_Query::parse_query() were to be run directly on its own, but WordPress itself never does that. Maybe some plugins do, but I don’t know why they would. Near as I can tell there’s no technical reason to use one over the other, but pre_get_posts is newer, much more widely used, and much better documented, officially and by third parties. I suspect parse_query is somewhat vestigial.

I’d suggest using pre_get_posts. Any code you see using parse_query should work as-is with pre_get_posts.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x