1

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!

2

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
}
0

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));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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