Skip to content
Advertisement

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. The posts from Canada and World are being displayed correctly, but nothing from United States. I have tried dumping var_dump($context['posts']); in the WordPress PHP file, which does return the posts from all of the categories including United States. When I use Timber’s {{ dump(post) }} in the Twig template to dump {{ dump(posts.united-states) }}, the following is displayed int(0). I have tried removing the hyphen from the category slug and updating the for loop, but this did not solve the issue.

Any ideas on what is causing this issue?

PHP code

$context = Timber::context();
$timber_post = new TimberPost();

$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

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

Advertisement

Answer

Have your tried accessing it with good old square brackets like below:

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

Quick example: https://twigfiddle.com/pbqq14

Loop example:

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

{{story}}

{% endfor %}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement