显示自定义 Post 类型类别

Display Custom Post Type Category

我已经设置了一个名为 "tours" 的自定义 Post 类型,其分类法 "tour_category" 仅特定于该 Post 类型。在分类法中,我设置了 4 个区域 Golf Breaks、Walking Tours 等...我想要实现的是将 Golf Breaks Taxomony 中的所有 Post 渲染到 golf.twig 模板中,但是我只好像得到的是页面未找到的错误。有人能用这个例子给我指明正确的方向吗?

$context = Timber::get_context();
$args = array(
// Get post type tours
    'post_type' => 'tours',
// Get all posts
    'posts_per_page' => -1,
// get post in "Golf Breaks" category
    'meta_query' => array(
        array(
            'key' => 'tour_category',
            'value' => 'Golf Breaks',
            'compare' => 'LIKE'
        )
    ),
// Order by post date
    'orderby' => array(
        'date' => 'DESC'
    ));

$context['Golf Breaks'] = Timber::get_posts( $args );

Timber::render( 'golf.twig', $context );

@richard:这条线会让你度过一段非常糟糕的时光....

$context['Golf Breaks'] = Timber::get_posts( $args );

因为数组的 属性 被 Twig 使用,所以你需要没有空格的东西(可能是小写)。试试....

$context['golf_breaks'] = Timber::get_posts( $args );

从那里您可以使用...

访问 Twig 中的数据
{% for post in golf_breaks %}
    <h1>{{ post.title }}</h1>
    <div>{{ post.content }}</div>
{% endfor %}

如果您没有看到任何内容,问题可能出在从 WP 获取帖子时。分类查询可能很困难,请尝试仅使用 get_posts 进行调试,以确保 WordPress 找到与您的查询匹配的帖子