Get post_meta for another post in Wordpress
For a site I’m rewriting I needed a way to get the meta data for a Wordpress post from outside the loop, and it seems that the functions that handle reading the meta data only work from within the loop. So I can up with this short little snippet of PHP code that gets the meta data for any post id you want.
PHP:
-
$wpdb->query(“SELECT meta_key, meta_value FROM {$wpdb->prefix}postmeta WHERE post_id=123″);
-
foreach ($wpdb->last_result as $result)
-
{
-
$meta[$result->meta_key] = $result->meta_value;
-
}
Be sure to replace post_id=123 in the query with whatever id you’re actually wanting to load.
This will create an array with all of the meta values in an associative array by the meta key.
Question, Comments...
Do you have more questions. Please either leave a comment below or join us in our new forum.