php - 如何在 WordPress 查询中获取分类类别的所有记录?

标签 php wordpress

我使用简单的内容类型插件并在 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)

  • 如果您必须运行自定义查询,请使用 WP_Queryget_posts

  • 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/

相关文章:

html - 侧边栏链接不可点击

wordpress - 对我的 WordPress 副本进行版本控制

wordpress - 如何在wordpress中的帖子下隐藏类别列表中的某些类别?

php - 细化搜索结果 [PHP/MySQL]

php - 使用 jQuery.ajax 在 MySQL 中存储表单数据

php - 使用 wp_dropdown_pages() 显示自定义帖子类型的下拉列表

php - 如何将 PHPUnit 与我的代码捆绑在一起?

php - MYSQL 计数基于两个表

php - Symfony2 禁用 HTML5 表单验证

php - SPL 自动加载和命名空间