WordPress is powerful. It is hard for anyone to deny that fact. It has years of programming and thought put into it so there is no doubt that it is a solid project. Sure, criticize the code as I roll my eyes because everyone criticizes the code. Get past that point and you realize utilizing an existing platform that focuses on users might just be the right thing to do. Battle tested so to speak.
I am writing the Hacking WordPress series to help gather my thoughts on what I am learning each week in the hopes that I can assist a newcomer in the future. This first post is about using meta_query to modify WP_Query. Come on in! The water is warm… sometimes salty.
While working on integrating the WP Event Calendar and WP User Alerts plugins at Flox – I had to learn about using meta queries so the calendar wouldn’t show alerted events. WP User Alerts adds postmeta data depending on if any users have been alerted. The modification to the WP Event Calendar was to be a small addition to exclude all events that have the user meta data in the post. Welcome WP_Meta_Query!
WP Meta Query is powerful! It allows you to modify queries and search for custom field data. In short, it allows you to restrict based on the data in wp_postmeta – this is
pretty really cool. For what I was trying to restrict by this ended up being the code for it:
I started to dig into the code and database and found that when I was adding my modification above it wasn’t working properly. This ended up being due to the way the meta query works is by having all the separate conditions groups together. For example, WP Event Calendar adds it’s own restrictions to only display events between the beginning and end of the month. When I first started programming I kept polluting the meta query and it was messing quite a few things up.
JJJ ended up patching WP Event Calendar due to this. This allows other plugin developers that want to hook into the code to do so without polluting the meta query like I did 😛
Summarizing a couple things that I learned about meta queries:
- WP_Meta_Query optimizes the query it will perform for you (we checked with EXPLAIN)
- There are no warnings if your multi-dimensional array is incorrect
- As a plugin developer you should wrap your meta queries in an additional array
- Inspecting the final SQL can and should be done just to make sense of it all!
Hope you enjoyed the article and please put any thoughts or comments in the empty-box-thingy below. Let me know how you utilize WP_Meta_Query or if you’ve had struggles in the past with it.