首页 > 解决方案 > 木材:如何在 archive.php 中查询单个自定义帖子类型的帖子

问题描述

我正在为 Wordpress 使用 Timber,当我在 archive.php 中使用自定义查询来获取自定义帖子类型的帖子时,它会返回多种帖子类型的帖子。

我在 page.php 中尝试了完全相同的查询,它运行良好。

这是我正在使用的查询:

global $paged;
    if (!isset($paged) || !$paged){
        $paged = 1;
    }
$args = array(
    'post_type' => 'horse',
    'orderby' => 'title',
    'order' => 'ASC',
    'posts_per_page' => 20,
    'paged' => $paged
);
$context['horses'] = new Timber\PostQuery( $args );

我希望返回所有帖子类型“马”的项目,但其他帖子类型也混入其中。

任何想法为什么会发生这种情况?


我不确定这是否相关,但我还在 StarterSite 类中的 functions.php 中添加了它,以便将我的自定义帖子类型添加到存档页面:

function namespace_add_custom_types( $query ) {
    if( is_category() || is_tag() && empty( $query->query_vars['suppress_filters'] ) ) {

        // Get all your post types
        $post_types = get_post_types();

        $query->set( 'post_type', $post_types );
        return $query;
    }
 }

这被添加到名为 的现有函数中__construct

add_filter( 'pre_get_posts', array($this, 'namespace_add_custom_types') );

标签: wordpress-themingtimber

解决方案


你如何在树枝文件中调用它?

{% for post in horses %}
{{ post.name }}
{% endfor %}

另外,您确定帖子类型名称是马而不是马吗?如果“post_type”中包含错误的帖子类型名称,它将显示所有帖子类型。


推荐阅读