Get Post ID by meta key and meta value

Not certain but often we are required to find post by specific meta key & value. In this tutorial i am showing one simple function that really helps to find that post ID by meta key & value.

Just open your function.php file and paste the below function:

So, here the above function need two parameter. One is your meta key name & another one is your value. Now we can call the function with specific meta key & value for instance we can say our meta key name ‘HOBBY’ & meta value is ‘WRITING’:

$postID = get_post_id_by_meta_key_and_value('hobby', 'writing');

That will return the post id. So you can make your stuff there now. Still have any confusion please feel free to drop message below.

Thanks.

This post has already been read 15549 times!

Mehedi Hasan

Cool WordPress Developer having much agile experience to develop any kind of WordPress sites & plugins. Also good in troubleshooting, fixing & making any kind of tweaks for WP site.

More Posts

Mehedi Hasan

Cool WordPress Developer having much agile experience to develop any kind of WordPress sites & plugins. Also good in troubleshooting, fixing & making any kind of tweaks for WP site.

5 thoughts on “Get Post ID by meta key and meta value

  • December 29, 2014 at 2:06 pm
    Permalink

    magnificent post and very informative. Go ahead Mehedi.

    Reply
  • August 15, 2015 at 10:30 pm
    Permalink

    Just what I needed, thanks so much!

    Reply
  • September 2, 2015 at 11:15 am
    Permalink

    What about if we try to find a post by a value contained inside the meta key amongst various values, separated by a comma? In my example, these values are also numeric.

    Reply
  • September 2, 2015 at 11:44 am
    Permalink

    Actually, I found teh solution. I used LIKE, simple enough!


    LIKE '%".esc_sql($value)."%'"

    Reply
  • June 18, 2019 at 3:09 pm
    Permalink

    For WP version >= 3.6 use in line 5
    $meta = $wpdb->get_results( $wpdb->prepare( “SELECT * FROM “.$wpdb->postmeta.” WHERE meta_key=%s AND meta_value=%s”, $key, $value ) );

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *