I am building a simple caching class and I want to use this class to cache queries. My initial thinking was to create a Query class and use this to handle all queries, meaning the Query class would use my Cache class to check if there is a saved query, otherwise it would run WP_query or $wpdb and cache the results.

So far so good and I want to take this one step further. What about the queries that wordpress runs by default ? Wordpress core functions won't use my class, so my question is this: Is there a way to hook into wordpress on query execution level ? The only hooks I was able to find were hooks about modifying the query, but what I want is a hook that handles the query execution itself (so that I can stop the query execution and retrieve the data that the query would search for from the cache).

For example, with wordpress structure I would guess that all queries would get executed at the end by $wpdb->query('FINAL BUILT QUERY HERE');. I don't know if this is true, but it is something that would make sense. So if this was the case, I would be looking for an action filter that receives the final query as a string or as an array of arguments and expects query results as a return (sounds like an insecure hook, but you get the idea). By default that hook would run $wpdb->query on the input data and that's where I come in to override this behaviour and add a detour for a cached query check before the actual execution.

I hope my example makes sense to understand what I am looking for, anyone knows a way to go about it ?

  • edited out the part about how people should reply and how don't. If you are not happy with the dynamics of this site, you just don't have to post your questions here. Commented Apr 6, 2017 at 7:53

1 Answer 1


In the class WP_Query, there is a hook posts_pre_query wich allow to set the result of a query before the DB call


  • Perfect, looks like this filter is new (WP version 4.6), which explains why my google searches failed. Cheers ! Commented Apr 6, 2017 at 12:34
  • Now I have to wait for a hook that overrides $wpdb->query execution I guess, but I'm glad for WP_Query, since it is the most important one. Commented Apr 6, 2017 at 12:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.