【问题标题】:Timber / TWIG spearate Templates for specific Categories特定类别的木材/ TWIG spearate 模板
【发布时间】:2018-12-09 02:43:12
【问题描述】:

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

archive.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 。有可能我理解错了吗?因为如果是这种情况,我的入门主题将无法按预期工作。 如果不是这个,我在文档中找不到动态解决方案。

【问题讨论】:

    标签: php wordpress twig categories timber


    【解决方案1】:

    它按预期工作。当is_category() 为真时,归档将通过get_query_var( 'cat' ) 获取类别ID,而不是类别名称。

    您可以更新 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 模板。考虑list of PHP templates on wphierarchy.com。在那里您可以看到您可以在主题根目录中使用 category.php 文件:

    $context = Timber::get_context();
    $context['title'] = single_cat_title( '', false );
    
    Timber::render( 'archive-category.twig', $context );
    

    【讨论】:

    • 对于预期用途,我更喜欢 archive.php 作为基础,而不是类别文件。我一有时间就去看看。 :) 已经谢谢了! (充分利用木材的功能是我的目标)
    • 我尝试了您的建议,但是如果我有一个名为“featured”的帖子类别并转到 .../category/featured,它将不会选择 archive-featured.twig 文件。但是,如果我将其设为 categoryid (archive-1.twig) 就可以了。但这不是我的意图。我希望它是类别的名称。请告诉我,我在这里遗漏了一些重要的东西。
    • 你是把现有的else if ( is_category() ) { 留在里面还是用我的建议替换它?
    • 我留下了,所以这些数字仍然有效。我想这就是问题所在。我稍后会尝试。顺便谢谢!真的很感谢你的时间?
    • 替换 else if ( is_category() ) {...} 成功了!非常感谢!
    猜你喜欢
    • 2015-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-22
    • 2017-04-15
    • 1970-01-01
    • 2023-04-01
    相关资源
    最近更新 更多