首页 > 解决方案 > 来自特定 WordPress 类别的帖子未在 Timber/Twig for 循环中显示

问题描述

我正在使用以下代码输出三个不同类别的帖子。来自加拿大和世界的帖子正确显示,但没有来自美国的帖子。我尝试var_dump($context['posts']);在 WordPress PHP 文件中转储,该文件确实返回了包括美国在内的所有类别的帖子。{{ dump(post) }}当我在 Twig 模板中使用 Timber's进行转储{{ dump(posts.united-states) }}时,会显示以下内容int(0)。我尝试从类别 slug 中删除连字符并更新for loop,但这并没有解决问题。

关于导致此问题的任何想法?

PHP 代码

$context = Timber::context();
$timber_post = new Timber\Post();

$query = array(
  // Canada, United States, and World categories
  'cat' => '3,4,6',
  'orderby' => 'title',
  'order' => 'ASC',
  'posts_per_page' => -1,
);

$posts = Timber::get_posts( $query );

$sorted_posts = array();

foreach ( $posts as $post ) {
  // Get first category of post
  $category = $post->category();

  // Fill post back to sorted_posts
  $sorted_posts[ $category->slug ][] = $post;
}

// Add sorted posts to context
$context['posts'] = $sorted_posts;

$context['post'] = $timber_post;
Timber::render( array( 'page-' . $timber_post->post_name . '.twig', 'page.twig' ), $context );

树枝模板代码

{% extends "base.twig" %}
{% block content %}
<section>
  <h2>Canada</h2>
  {% for story in posts.canada %}
    <article class="story" id="story-{{ story.ID }}">
    </article>
  {% endfor %}
</section>
<section>
  <h2>United States</h2>
  {{ dump(posts.united-states) }}
  {% for story in posts.united-states %}
    <article class="story" id="story-{{ story.ID }}">
    </article>
  {% endfor %}
</section>
<section>
  <h2>The World</h2>
  {% for story in posts.world %}
    <article class="story" id="story-{{ story.ID }}"> 
    </article>
  {% endfor %}
</section>
{% endblock %}

标签: phphtmlwordpresstwigtimber

解决方案


您是否尝试过使用良好的旧方括号访问它,如下所示:

{{ dump(posts['united-states']) }}

快速示例:https ://twigfiddle.com/pbqq14

循环示例:

{% for story in posts['united-states'] %}

{{story}}

{% endfor %}

推荐阅读