简体   繁体   English

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

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

I am using the following code to output posts from three different categories.我将以下代码用于来自三个不同类别的 output 帖子。 The posts from Canada and World are being displayed correctly, but nothing from United States.来自加拿大和世界的帖子正确显示,但没有来自美国的帖子。 I have tried dumping var_dump($context['posts']);我试过转储var_dump($context['posts']); in the WordPress PHP file, which does return the posts from all of the categories including United States.在 WordPress PHP 文件中,它确实返回了包括美国在内的所有类别的帖子。 When I use Timber's {{ dump(post) }} in the Twig template to dump {{ dump(posts.united-states) }} , the following is displayed int(0) .当我在 Twig 模板中使用 Timber 的{{ dump(post) }}转储{{ dump(posts.united-states) }}时,显示以下int(0) I have tried removing the hyphen from the category slug and updating the for loop , but this did not solve the issue.我尝试从类别 slug 中删除连字符并更新for loop ,但这并没有解决问题。

Any ideas on what is causing this issue?关于是什么导致这个问题的任何想法?

PHP code 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 template code 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 %}

Have your tried accessing it with good old square brackets like below:您是否尝试过使用良好的旧方括号访问它,如下所示:

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

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

Loop example:循环示例:

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

{{story}}

{% endfor %}

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

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