繁体   English   中英

来自特定 WordPress 类别的帖子未在 Timber/Twig for loop 中显示

[英]Posts from specific WordPress category not displaying in Timber/Twig for loop

我将以下代码用于来自三个不同类别的 output 帖子。 来自加拿大和世界的帖子正确显示,但没有来自美国的帖子。 我试过转储var_dump($context['posts']); 在 WordPress PHP 文件中,它确实返回了包括美国在内的所有类别的帖子。 当我在 Twig 模板中使用 Timber 的{{ dump(post) }}转储{{ 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 );

Twig模板代码

{% 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 %}

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

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

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

循环示例:

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

{{story}}

{% endfor %}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM