首页 > 解决方案 > 特定类别的木材/ TWIG spearate 模板

问题描述

所以在入门主题中,我们有这个:

存档.php:

$templates = array( 'archive.twig', 'index.twig' );

$context = Timber::get_context();

$context['title'] = 'Archive';
if ( is_day() ) {
    $context['title'] = 'Archive: ' . get_the_date( 'D M Y' );
} else if ( is_month() ) {
    $context['title'] = 'Archive: ' . get_the_date( 'M Y' );
} else if ( is_year() ) {
    $context['title'] = 'Archive: ' . get_the_date( 'Y' );
} else if ( is_tag() ) {
    $context['title'] = single_tag_title( '', false );
} else if ( is_category() ) {
    $context['title'] = single_cat_title( '', false );
    array_unshift( $templates, 'archive-' . get_query_var( 'cat' ) . '.twig' );
} else if ( is_post_type_archive() ) {
    $context['title'] = post_type_archive_title( '', false );
    array_unshift( $templates, 'archive-' . get_post_type() . '.twig' );
}

$context['posts'] = new Timber\PostQuery();
Timber::render( $templates, $context );

据我了解,如果我导航到http://.......com/index.php/category/newcategory/它应该获取archive-newcategory.twig文件作为模板。另一个例子,如果我去http://.......com/index.php/category/anothercat/它应该去获取archive-anothercat.twig。有可能我理解错了吗?因为如果是这种情况,我的入门主题将无法按预期工作。如果不是这个,我在文档中找不到动态解决方案。

标签: phpwordpresstwigcategoriestimber

解决方案


它按预期工作。如果is_category()为 true,存档将通过 获取类别 ID get_query_var( 'cat' ),而不是类别名称。

您可以更新archive.php中的代码以添加您要使用的 Twig 模板。例如:

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 模板。考虑wphierarchy.com 上的 PHP 模板列表。在那里您可以看到您可以在主题根目录中使用category.php文件:

$context = Timber::get_context();
$context['title'] = single_cat_title( '', false );

Timber::render( 'archive-category.twig', $context );

推荐阅读