如何解决来自特定 WordPress 类别的帖子未显示在 Timber/Twig for 循环中
我使用以下代码输出来自三个不同类别的帖子。来自加拿大和世界的帖子显示正确,但没有来自美国的帖子。我曾尝试在 wordpress PHP 文件中转储 var_dump($context['posts']);
,它确实返回了所有类别的帖子,包括美国。当我在 Twig 模板中使用 Timber 的 {{ dump(post) }}
转储 {{ dump(posts.united-states) }}
时,会显示以下 int(0)
。我已尝试从类别 slug 中删除连字符并更新 for loop
,但这并没有解决问题。
对导致此问题的原因有任何想法吗?
$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 %}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。