Custom Select Query by meta key and cat id

174 views Asked by At

I have this custom query that get the expiry date of the post and orders post by that. How do I amend it to only list from a certain category id e.g. '20'

$querystr = "
    SELECT wposts.*
    FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
    WHERE wposts.ID = wpostmeta.post_id
    AND wpostmeta.meta_key = 'es_ape_expiry'
    ORDER BY wpostmeta.meta_value ASC
    ";

 $pageposts = $wpdb->get_results($querystr, OBJECT);

Many Thanks !

1

There are 1 answers

0
Bhumi Shah On BEST ANSWER

Try following query and replace $cat_id with 20

SELECT wposts.*
FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
JOIN $wpdb->term_relationships tr ON (p.ID = tr.object_id)
JOIN $wpdb->term_taxonomy tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id)
JOIN $wpdb->terms t ON (tt.term_id = t.term_id)
WHERE wposts.ID = wpostmeta.post_id
AND wpostmeta.meta_key = 'es_ape_expiry' 
AND tt.taxonomy = 'category'
AND t.term_id = $cat_id
ORDER BY wpostmeta.meta_value ASC