Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

UPDATE

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
add comment

1 Answer

Why don't you just do:

<?php 
global $post;
$args = array( 
    'post_type' => 'post',
    'post_status' = 'publish',
    'posts_per_page' => '10',
    'meta_query' => array(
        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
add comment

Your Answer

 
discard

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.