如何使用多个参数执行 WP_Query? [英] How do I execute a WP_Query with multiple arguments?

查看:27
本文介绍了如何使用多个参数执行 WP_Query?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我已经试过了:

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

?>

推荐答案

您需要比较自定义字段的值并执行meta_query.试试下面的代码:

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

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

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

这篇关于如何使用多个参数执行 WP_Query?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆