我使用简单的内容类型插件并在 WP 调用食谱中创建了帖子类型。我还在其中添加了一个分类类别并创建了 4 个类别,例如 Starter、Drinks 等。
现在在 WP 查询中我需要获取启动器的所有记录。 那我怎样才能得到它呢?
我正在使用这个查询,但它不起作用。它正在提供 Recipes 帖子类型的所有记录 这是查询
$recipes = query_posts('post_type=recipes&taxonomy=recipescategory&category_name=Starters');
最佳答案
您的代码中有很多错误,并且对类别有误解。
- 切勿使用
query_posts
构建自定义查询
Note: This function isn't meant to be used by plugins or themes. As explained later, there are better, more performant options to alter the main query. query_posts() is overly simplistic and problematic way to modify main query of a page by replacing it with new instance of the query. It is inefficient (re-runs SQL queries) and will outright fail in some circumstances (especially often when dealing with posts pagination)
category_name
采用类别 slug,不是名称。参数名是骗人的属于自定义分类法的“类别”称为术语。我写了一篇文章,我也将其包含在您可以查看的法典中 here , 它描述了差异。
要从自定义分类中检索帖子,您需要使用
tax_query
.类别参数在这里不起作用
综上所述,创建您的查询,使其看起来像这样
$args = array(
'post_type' => 'recipes',
'tax_query' => array(
array(
'taxonomy' => 'recipescategory',
'field' => 'name',
'terms' => 'Starters',
),
),
);
$query = new WP_Query( $args );
if( $query->have_posts() ){
while( $query->have_posts() ) {
$query->the_post();
//Your loop elements
}
wp_reset_postdata();
}
关于php - 如何在 WordPress 查询中获取分类类别的所有记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26627839/