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: , , , , ,

Leave a comment