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

I have this SQL query which is building an array of wordpress posts...

$query = "select $wpdb->posts.* from $wpdb->posts,$wpdb->terms,$wpdb->term_taxonomy,$wpdb->term_relationships where $wpdb->terms.term_id in (".$catId.") and $wpdb->terms.term_id = $wpdb->term_taxonomy.term_id and $wpdb->term_taxonomy.taxonomy = 'pcategory' and $wpdb->term_taxonomy.term_taxonomy_id = $wpdb->term_relationships.term_taxonomy_id AND $wpdb->posts.post_status = 'publish' and $wpdb->term_relationships.object_id = $wpdb->posts.ID and $wpdb->posts.ID != ".$post->ID." group by $wpdb->posts.ID order by $wpdb->posts.ID LIMIT 0 ,$limit";

I need to modify this to allow me to add a condition that only posts with a specific custom field value, say 'Apple' are included in the array.

Can anyone point me in the right direction?


I have tried to modify it to this....

$query = "select $wpdb->posts.* from $wpdb->posts,$wpdb->terms,$wpdb->term_taxonomy,$wpdb->term_relationships where $wpdb->terms.term_id in (".$catId.") and $wpdb->terms.term_id = $wpdb->term_taxonomy.term_id and $wpdb->term_taxonomy.taxonomy = 'pcategory' and $wpdb->term_taxonomy.term_taxonomy_id = $wpdb->term_relationships.term_taxonomy_id AND $wpdb->posts.post_status = 'publish' and $wpdb->postmeta.meta_key = 'fruit' and $wpdb->postmeta.meta_value= 'apple' and $wpdb->term_relationships.object_id = $wpdb->posts.ID and $wpdb->posts.ID != ".$post->ID." group by $wpdb->posts.ID order by $wpdb->posts.ID LIMIT 0 ,$limit";

I was assuming that this would narrow down the search to only the posts that have a value of 'apple' for the custom field named 'fruit' but its not working

share|improve this question

Why don't you just do:

global $post;
$args = array( 
    'post_type' => 'post',
    'post_status' = 'publish',
    'posts_per_page' => '10',
    'meta_query' => array(
            'key' => 'fruit',
            'value' => 'apple'
$custom_query = new WP_Query( $args );
while( $custom_query->have_posts() ): $custom_query->the_post(); ?>

<?php the_title(); ?>

<?php endwhile; wp_reset_query(); ?>
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.