php - 来自特定 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 %}
解决方案
您是否尝试过使用良好的旧方括号访问它,如下所示:
{{ dump(posts['united-states']) }}
快速示例:https ://twigfiddle.com/pbqq14
循环示例:
{% for story in posts['united-states'] %}
{{story}}
{% endfor %}
推荐阅读
- r - 如何修复 - 找不到对象“Inputs2”。并在 R Shiny 中获得最终图
- oauth-2.0 - 如何为 Camel 路由存储 OAuth 令牌
- mysql - 如何在 MySQL 中显示每组的最新记录
- r - Getting R observations back to NodeJS using "sort"
- r - Boxplot/ Box & Whisker 帮助 ggplot2 (R) 需要删除重复项,同时在一个图上绘图
- javascript - 将括号内的字符串传递给另一个字符串
- oracle - 具有多个节点的 Oracle 分层查询
- java - 双击后jar文件什么也不做
- delphi - 如何在 Delphi 10.2 中使用 ToolsAPI 获取当前项目的版本号
- debian - dh_link 不覆盖另一个包的符号链接