How do I execute a WP_Query with multiple argument

2019-09-09 08:28发布

问题:

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

?>

回答1:

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.



标签: php wordpress