I want to use custom post type in my custom SQL query, but, when I add the custom post type im my query, I get no results.

Where's my probelm ?

This is the code I've tried

$top5_ov_performance = $wpdb->get_results("SELECT post_id,meta_value FROM ".$wpdb->prefix."postmeta WHERE meta_key = 'sd_top5_overclocing' AND (post_type = 'cpu')  ORDER BY meta_value DESC LIMIT 0,5 ");

I have also tried this post_type = 'cpu' instead of (post_type = 'cpu') and and instead of AND

  • there's no post_type column in the post meta table, post type is associated with posts, not meta data.
    – Milo
    Dec 11, 2014 at 23:33
  • got thanks for replay , but how can i use for this query ? i really need that! Dec 11, 2014 at 23:35

2 Answers 2


If you're trying to get all meta values for a key within a specific post type, you can do something like this in a single query:

SELECT post_id, meta_value FROM $wpdb->postmeta pm, $wpdb->posts p
WHERE meta_key = 'sd_rating' and pm.post_id = p.ID  AND p.post_type = 'cpu'

I have found a way :

global $wpdb,$post;
                                    $query_ids = $wpdb->get_results("SELECT ID FROM ".$wpdb->prefix."posts WHERE (post_type = 'cpu') LIMIT 0,10");
                                        foreach ($query_ids as $query_id) {
                                            $query = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."postmeta WHERE post_id = ".$query_id->ID." AND meta_key = 'sd_rating' ORDER BY meta_value LIMIT 0,10");
                                                foreach ($query as $value) {
                                                    echo $value->meta_value;
  • Please accept your own answer Dec 12, 2014 at 6:51

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.