[wp-hackers] How to get the meta_ID?

Andrew Nacin wp at andrewnacin.com
Fri Jan 15 16:33:34 UTC 2010

> There is no built-in function that I know of so here is my humble attempt
> to get the meta_id *by meta_key*:

$wpdb->get_var( $wpdb->prepare("SELECT meta_id FROM $wpdb->postmeta WHERE
> post_id = %d AND meta_key = %s", $post_id, $meta_key) );

A post can have more than one row in the postmeta table for each meta_key.
Not only can they have different values, but they can also have the same
value (and thus only differ in meta_id). There is a ticket in Trac to
prevent duplicates on meta_value + meta_key + post_id (
), but either way you would still need to also check the meta value when
trying to find the corresponding meta_id, as having multiple values per key
per post is perfectly valid.

You should probably avoid using meta_id at all costs and stick to the API if
at all possible, though.

More information about the wp-hackers mailing list