How to get the Meta ID by Meta Key

The problem

Well, I guess it’s not too often that you need to get the ID of a particular meta entry from the postmeta table in WordPress. However, Matthew on the wp-hackers mailing list needed exactly that.

The solution

So here’s a function to get the ID of a meta entry based on the given meta_key:

function get_mid_by_key( $post_id, $meta_key ) {
  global $wpdb;
  $mid = $wpdb->get_var( $wpdb->prepare("SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = %s", $post_id, $meta_key) );
  if( $mid != '' )
    return (int)$mid;

  return false;
}

What does it do?

The function returns the ID of the meta entry in the postmeta table or false if no results are returned. Invoke the function like so:

get_mid_by_key( your_post_id, 'your_meta_key' );

Requirements

  • WordPress 2.3 and above

Tags: , , , , ,

6 comments

  1. Oliver Schlöbe

    [New Blog Post] How to get the Meta ID by Meta Key http://bit.ly/5L71TS
    #wp

  2. [New Blog Post] How to get the Meta ID by Meta Key http://bit.ly/5L71TS
    #wp

  3. Thanks really substantially to your good write-up;this can be the kind of matter that keeps me going via out these day. I’ve been seeking all-around for this web page following getting referred to them from a colleague and was pleased when I discovered it immediately after looking for some time. Currently being a avid blogger, I’m cheerful to see others taking initivative and contributing on the community. I’d prefer to remark to show my approval for the put up since it is extremely challenging to perform, and many bloggers usually do not get acceptance they deserve. We’re sure I’ll check out once more and will send a few of my friends.

  4. This helped so much!

    Used it in this modified code: http://snipplr.com/view/46538/

    Thanks!

  5. Thanks for the information provided! I was looking for this information for quite some time, but I wasn’t able to see a dependable source.

Leave a comment