【问题标题】:How to name WordPress template for category AND custom taxonomy如何为类别和自定义分类法命名 WordPress 模板
【发布时间】:2019-03-25 15:06:39
【问题描述】:

我正在使用自然摄影网站的物种类别和称为位置的自定义分类法来捕捉照片的拍摄地点。

当类别为“flora”且位置为“south-america”时,我想加载不同的模板,因此我将模板命名为 category-flora-taxonomy-location-south-africa.php。

如果我去http://mywebsite/species/flora/location/south-africa/ 加载正确的帖子,但不是我的模板。我确实通过保存永久链接刷新了重写规则。我还为我的模板尝试了以下文件名,结果相同:

category-flora-taxonomy-location-south-africa.php
category-flora-taxonomy_location-south-africa.php
taxonomy-location-south-africa-category-flora.php
taxonomy-location-south-africa_category-flora.php

WordPress 是否支持在这样的模板名称中混合类别和自定义分类法,还是我必须显式加载我的模板?如果是这种情况,有什么方法可以做到这一点?

【问题讨论】:

    标签: wordpress templates categories custom-taxonomy


    【解决方案1】:

    该规则不是 WP 的一部分,但我们可以构建它...

    在functions.php中添加并调整:

    add_filter( 'taxonomy_template', function ( $template )
    {
    
        // get category and term slugs from post object via get_queried_object()
    
        $custom_template = 'category-{$category}-taxonomy-{$taxonomy}-{$term}.php';
        $locate_template = locate_template( $custom_template );
    
        if ( !$locate_template )
            return $template;
    
        return $template = $locate_template;
    }
    

    【讨论】:

      【解决方案2】:

      对于存档页面,get_queried_object() 只获取类别,而不是我还必须检查的自定义分类。所以我改用全局变量 $category_name 和 $location 。这是修改后的代码:

      add_filter('taxonomy_template', function( $template ){
          global $category_name, $location;
          if ( ($category_name == "flora") && $location == "south-africa" ) {
              $custom_template = 'category-flora-taxonomy-location-south-africa.php';
              $locate_template = locate_template( $custom_template );
          };
          if ( !$locate_template )
              return $template;
      
          return $template = $locate_template;
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-22
        • 2014-08-30
        • 1970-01-01
        • 2022-07-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多