如何使用多个参数执行WP_Query?

时间:2014-07-07 19:38:04

标签: php wordpress

我正在尝试做一个WP_Query,我希望循环只在帖子类型是书籍时才能执行,而流派是$ genre中的文本。我一直收到错误,因为它显示了书籍类型中的所有帖子,而不是所需的特定类型。

我试过这个:

<?php
$genre ="suspense";
$args = array('post_type' => 'books','genre' => $genre);     
        //Define the loop based on arguments     
        $loop = new WP_Query( $args );   
        //Display the contents   
        while ( $loop->have_posts() ) : $loop->the_post();

?>

1 个答案:

答案 0 :(得分:1)

您需要比较自定义字段的值并执行meta_query。请尝试以下代码:

<?php
$genre ="suspense";
$args = array(
    'post_type' => 'books',
    'meta_query' => array(
        array(
            'key' => 'genre',
            'value' => $genre,
            'compare' => '='
        )
    )
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();   
?>

在此处阅读有关WordPress Codex的更多信息:http://codex.wordpress.org/Class_Reference/WP_Query