I've been pulling my hair out trying to figure out how to do this. I'v created a custom field called cp_country. Now each record in Mysql has a value for cp_country. The problem is i don't understand how Wordpress indexes data into MySql.

For example look here

enter image description here

Normally, i'd be used to fetching rows like SELECT * FROM table WHERE cp_country='United Kingdom' But as you can see the results aren't one row, the attributes are listed by per row joined by a post id.

How do i get a results WHERE cp_country='United Kingdom'?

For example a set of results would each have cp_country,cp_street,cp_price.

1 Answer 1


Bulk of WP's native data structures aren't meant for direct MySQL access. They are typically accessed via PHP APIs which take care of MySQL generation/execution and many more things, such as allowing to filter data, caching it for performance, and so on.

Your issue here is that from MySQL point of view meta values aren't related to each other, but only to their posts. Also note that it's perfectly valid to have multiple meta values with same meta key, it's not constrained to be unique.

So WP mechanics would be to:

  1. Retrieve all posts (or just post IDs) for United Kingdom via API.
  2. Loop through the set and retrieve necessary meta information via API.

Once you get that working you can take a look on queries generated under the hood and move on to something closer to database, using them.

  • Just to add here, the proper function to retrieve post meta in wordpress is get_post_meta which can be used to retrieve a single result, or all results, with the specified meta_key. You should also be using add_post_meta or update_post_meta to create these in your database to begin with.
    – Matt Keys
    Nov 8, 2014 at 14:41

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.