As much as I am a fan of certain WordPress APIs for querying the database such as:
- WP_Query,
- WP_User_Query,
- WP_Meta_Query,
- and so on
I’m also a fan of querying directly against the database when needed.
As you’ll notice, there’s a consistent way that I go about doing this and since there are times where I’ve been doing this more frequently, as of late, here is a basic format for working with database queries in WordPress.
If I do this, though, there are generally do things that I keep in mind:
- always make sure the query is parameterized (especially in the case of user input),
- return in the information in the form of an associative array.
The first case is for security; the second is more or less for convenience to make iterating through the data simpler via PHP array functions.





