Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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;
}
}
}
@JasonMuk

This comment has been minimized.

Copy link

@JasonMuk JasonMuk commented Mar 22, 2013

is this code get the ID is the last post when have more result?

@manolof

This comment has been minimized.

Copy link

@manolof manolof commented Jul 29, 2014

Notice: wpdb::escape is deprecated since version 3.6! Use wpdb::prepare() or esc_sql() instead. in /Users/emmanouilgketsim/htdocs/svn/infosource.culturalcare.com/wp-includes/functions.php on line 3078

For WP version >= 3.6, use esc_sql() instead of $wpdb->escape and it should not throw any notice.

@solankin1576

This comment has been minimized.

Copy link

@solankin1576 solankin1576 commented Apr 12, 2016

Thanks for it

@abdechakour

This comment has been minimized.

Copy link

@abdechakour abdechakour commented Jul 15, 2017

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment