WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

some of my posts have the post meta of "project_id". How can I retrive all the posts which have the meta key of "project_id" ? I tried:

$meta_key = 'project_id';
return $wpdb->get_var($wpdb->prepare("SELECT ID FROM $wpdb->postmeta WHERE meta_key = %s", $meta_key));

It returns nothing. Please help! Thanks!

share|improve this question
up vote 1 down vote accepted

As simple as this: $the_posts_you_want = get_posts( array( 'meta_key' => 'project_id' ) );

foreach ( $the_posts_you_want as $post )
    // Do whatever you need in here... 
    // Read further how to inspect the post object: http://wordpress.stackexchange.com/questions/13063/how-to-inspect-global-variables-in-wordpress
    // echo each meta key
    echo $post->whatever;
    // or save it into a new array for further processing
    $project_ids = array();
    $project_ids[] = $post->whatever;
// If you saved them into an array, you can continue here...
foreach ( $project_ids as $id )
    // do stuff
share|improve this answer
sorry for my question misleading-- I want all the "project_id", not the posts. – Jenny May 28 '11 at 14:07
See Edit ...... – kaiser May 28 '11 at 14:46
That's perfect! Thanks! – Jenny May 28 '11 at 14:57
sorry, I'm new to this community, I don't know how to add as solution. Just signed up and voted the answer. It really helps a lot. – Jenny May 29 '11 at 5:38
just figured it out-- it's the gray check :-) – Jenny May 29 '11 at 5:43

Your query return nothing since there is no field ID in the postmeta table so it really should be post_id :

$meta_key = 'project_id';
return $wpdb->get_var($wpdb->prepare("SELECT post_id FROM $wpdb->postmeta WHERE meta_key = %s", $meta_key));
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.