How do I execute a WP_Query with multiple argument

2019-09-09 08:19发布

I am trying to do a WP_Query where I want the loop to execute only if the post type is books and genre is the text in $genre. I keep getting an error as it displays all the posts in the books post type instead of the particular genre required.

I have tried this:

<?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();

?>

标签: php wordpress
1条回答
2楼-- · 2019-09-09 08:30

You need to compare the value of the custom field and perform a meta_query. Try the following code:

<?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();   
?>

Read more on the WordPress Codex here: http://codex.wordpress.org/Class_Reference/WP_Query.

查看更多
登录 后发表回答