【发布时间】:2019-11-18 19:37:34
【问题描述】:
我在 WordPress 中有一个父类别页面,该页面显示一个帖子及其下方的四个子类别。四个子类别页面将共享相同的 HTML 和逻辑,但与父类别不同。父类别使用 category.php 和 category.twig 来处理其 HTML 和内容的显示。请参阅下面的代码。我如何告诉 WordPress 和 Timber 使用 category-child.php 和 category-child.twig (示例名称)作为父类别的孩子(slug:故事)。我知道我可以为每个子 slug 或 ID 使用 category-slug.php 或 category-id.php,但这需要将相同的代码添加到四个(或更多)不同的 PHP 和 Twig 文件中,这并不理想。
category.php
/**
* @package WordPress
* @subpackage gerryfeehan
* @since 1.0.0
*/
$templates = array( 'category.twig', 'index.twig' );
$context = Timber::context();
$args = array(
'cat' => '7,5,3,4,6',
'numberposts' => 1,
'orderby' => 'date',
'order' => 'DESC',
);
$context['stories'] = Timber::get_posts($args);
$context['categories'] = Timber::get_terms('category');
$categories = get_categories(
array(
'hide_empty' => '0',
'parent' => 7,
'orderby' => 'id',
'order' => 'ASC'
)
);
// $context['categories'] = $categories;
// Updated code with suggestions from Tomek
$category = get_queried_object(); // will give you current WP_Term
if( $category->parent == 0 ) {
// parent category
$templates = array( 'category.twig' );
$context['categories'] = $categories;
} else {
// child category
$templates = array( 'category-map.twig' );
$context['categories'] = $categories;
}
// Timber::render( array( 'category.twig', 'index.twig' ), $context );
Timber::render( $templates, $context );
category.twig
{% extends "base.twig" %}
{% block content %}
<section class="stories">
<h2>Stories</h2>
{% for story in stories %}
<article class="story" id="story-{{ story.ID }}">
{% if story.thumbnail.src %}
<figure>
<img src="{{ story.thumbnail.src }}" class="" alt="{{ story.thumbnail.alt }}" />
{% if story.thumbnail.caption %}
<figcaption>{{ story.thumbnail.caption }}</figcaption>
{% endif %}
</figure>
{% endif %}
<h3 class="story__heading">
<a href="{{ story.link }}">
{{ story.title }}
</a>
</h3>
<div class="story__meta">
<time class="">{{ story.date }}</time>
</div>
<div class="story__content">
{{ story.preview.read_more(false) }}
</div>
</article>
{% endfor %}
</section>
{% if function(cat_is_ancestor_of(7, 5)) %}yolo{% endif %}
{% for category in categories %}
<div class="category">
<figure>
<figcaption>
{{ category.name }}
</figcaption>
{{ category.description }}
</figure>
</div>
{% endfor %}
{% endblock %}
以下代码可以添加到 archive.php 文件中,但我不确定如何扩展它以满足我的需要。
else if ( is_category() ) {
$term = new Timber\Term( get_queried_object_id() );
$context['term'] = $term;
$context['title'] = single_cat_title( '', false );
array_unshift( $templates, 'archive-' . $term->slug . '.twig' );
}
完整的父子类别结构
父级:故事 儿童:露营美国、加拿大、美国和世界。
有什么想法吗?
【问题讨论】:
标签: php wordpress twig wordpress-theming timber