I'm trying to get a complete understanding of how WordPress works with databases. I've read the documentation but I'm getting confused by all the different approaches available. So far my understanding is this (layered by level of abstraction from the database):


"WP_API" (for REST/HTTP data access)


"get/add/update/delete" functions (e.g., get_post_meta())


"WP_Query" class (access data without writing SQL)


"$wpdb" object (access data by writing direct SQL)


"MySQL" database (persistence storage)

Is this ordered correctly? Am I missing anything, what else is there? It seems to me any direct SQL query can be executed with $wpdb. Then there's an abstraction WP_Query on top of $wpdb for people who don't want to write SQL. Then yet again there's another abstraction on top of WP_Query for people who want to use simple functions. And finally there's the new WP REST API which can do it all and more.

I could just use $wpdb (or WP_API) for everything can't I? Why bother with WP_Query or the get/add/update/delete functions? Doesn't that just add more unnecessary bloat/complexity?


There's some overlap, but each isn't an abstraction of the previous, and there are definitely some things you don't want to do outside of the API. Most things, actually!

WP_Query is for retrieving posts and pages, it doesn't update anything, and it doesn't fetch data that isn't a post or page. The higher level API functions that fetch posts and pages use WP_Query behind the scenes, but WordPress has many other kinds of data (post meta, taxonomies, users, user meta), which WP_Query doesn't directly deal with.

You can't use $wpdb directly for most things because you'll mostly break things. If you've spent any time with WordPress, you've probably heard of Hooks, Actions, and Filters. Querying the database directly bypasses that whole system, so any modification of queries, fetched data, caches, or actions to be carried out when a particular event happens will all break.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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