Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abdechakour/bf89095143b583c9d007cb9c3f174820 to your computer and use it in GitHub Desktop.
Save abdechakour/bf89095143b583c9d007cb9c3f174820 to your computer and use it in GitHub Desktop.
WordPress: Get post id by meta key and value
<?php
if (!function_exists('get_post_id_by_meta_key_and_value')) {
/**
* Get post id from meta key and value
* @param string $key
* @param mixed $value
* @return int|bool
* @author David M&aring;rtensson <david.martensson@gmail.com>
*/
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;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment