Categories: Wordpress Basics

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:

if (!function_exists('get_post_id_by_meta_key_and_value')) {

 function get_post_id_by_meta_key_and_value($key, $value) {
 global $wpdb;
 $meta = $wpdb->get_results("SELECT * FROM `".$wpdb->postmeta."` WHERE meta_key='".$wpdb->escape($key)."' AND meta_value='".$wpdb->escape($value)."'");
 if (is_array($meta) && !empty($meta) && isset($meta[0])) {
  $meta = $meta[0];
  } 
 if (is_object($meta)) {
  return $meta->post_id;
  }
 else {
  return false;
  }
 }
}

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.

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.

Share
Published by
Mehedi Hasan

Recent Posts

WP Share A Friend – A Way to Capture Lead

What is Lead Capture: In general sense lead capture designates a process or way of…

5 years ago

Unlimited Modal POPUPS on MouseClick

Introduction Unlimited Modal POPUPS on MouseClick: Everyone knows about popup during site visits and most…

5 years ago

WordPress Pregnancy Calculator Plugin

Brief about Pregnancy Calculator : This WordPress Pregnancy Calculator plugin allows users to display an…

5 years ago

Interactive Service Plugin with Hover Effects VC

Introduction About this Service Plugin: This Visual Composer Service Plugin works as an addon to…

6 years ago

WP Dynamic Query String

Introduction of Dynamic Query String : This plugin allows user to set dynamic query string…

6 years ago

How to make scroll PDF in iFrame for iPAD Safari

There is an occasional bug for iPhone and iPad even they are designed as well and…

7 years ago