-1

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

1

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

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.