自定义查询,多个自定义密钥

时间:2011-01-16 作者:Martin-Al

我需要得到有两个元值的帖子。

它尝试了以下代码,但结果为空

<?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);
?>
有什么想法吗?我试着四处寻找,但没有找到任何适合我的/

谢谢你的帮助

2 个回复
最合适的回答,由SO网友:goldenapples 整理而成

我不是SQL专家,但我认为您可能需要加入两次才能从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
 "; 

SO网友:Annika Backstrom

与新的类似tax_query 选择query_posts(), WordPress 3.1将添加meta_query 参数:

query_posts( array(
    \'meta_query\' => array(
        array(
            \'key\' => \'article_level\',
            \'value\' => \'Hovedsak\',
        ),
        array(
            \'key\' => \'article_genre\',
            \'value\' => \'X6.no (Spill og underholdning)\',
        ),
    ),
) );
现在还不太清楚,但值得一提。

结束

相关推荐