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 need to get posts that have two meta-values.

It tried the following code, but this is getting empty result

<?php
 $featuredquery = "
    SELECT wposts.*
    FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
    WHERE wposts.ID = wpostmeta.post_id
    AND (wpostmeta.meta_key = 'article_level' AND wpostmeta.meta_value = 'Hovedsak')
    AND (wpostmeta.meta_key = 'article_genre' AND wpostmeta.meta_value = 'X6.no (Spill og underholdning)')
    AND wposts.post_status = 'publish'
    AND wposts.post_type = 'post'
    AND wposts.post_date < NOW()
    ORDER BY wposts.post_date DESC
    LIMIT 0 , 4
 "; 

 $featuredposts = $wpdb->get_results($featuredquery, OBJECT);
?>

Any ideas for this? I tried searching around, but didn't find anything that suited me.. :/

Thanks for all help

share|improve this question

2 Answers 2

up vote 4 down vote accepted

I'm not an SQL expert, but I would think you might have to JOIN twice to pick two distinct rows out of wp_postmeta:

 $featuredquery = "
    SELECT wposts.*
    FROM $wpdb->posts wposts
    JOIN $wpdb->postmeta article_level ON
      ( wposts.ID = article_level.post_id AND
        article_level.meta_key = 'article_level' )
    JOIN $wpdb->postmeta article_genre ON 
      ( wposts.ID = article_genre.post_id AND
        article_genre.meta_key = 'article_genre' )
    WHERE article_level.meta_value = 'Hovedsak'
    AND article_genre.meta_value = 'X6.no (Spill og underholdning)'
    AND wposts.post_status = 'publish'
    AND wposts.post_type = 'post'
    AND wposts.post_date < NOW()
    ORDER BY wposts.post_date DESC
    LIMIT 0 , 4
 "; 
share|improve this answer
    
would be correct. I've done queries like that before and they work without a hitch. –  Manny Fleurmond Jan 17 '11 at 15:45
    
@Manny Fleurmond Which would be correct? The way he originally wrote the query, or this way I rewrote it? –  goldenapples Jan 17 '11 at 18:32
    
Hmm, I would guess that this was a solution, but it didn't work for me. It just gave me an empty result.. –  Martin-Al Jan 17 '11 at 18:53

Similar to the new tax_query option to query_posts(), WordPress 3.1 will add a meta_query argument:

query_posts( array(
    'meta_query' => array(
        array(
            'key' => 'article_level',
            'value' => 'Hovedsak',
        ),
        array(
            'key' => 'article_genre',
            'value' => 'X6.no (Spill og underholdning)',
        ),
    ),
) );

Not quite here yet, but worth mentioning.

share|improve this answer

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.