WordPress:对给定类别

时间:2016-09-21 21:42:09

标签: wordpress

为单个类别档案或帖子制作模板不是问题。

但是我不能谷歌,在Codex中找到或者弄清楚自己如何为给定类别中的所有帖子分配自定义模板。

3 个答案:

答案 0 :(得分:0)

您可以在WordPress.org网站上查找此信息。

这是我在快速Google Search

时发现的

基本上你有这些模板文件(这些也是WordPress首先要查找的顺序):

1)category-slug.php
2)category-ID.php
3)category.php

答案 1 :(得分:0)

我结束了下面的拐杖。

将以下内容放入functions.php中,以检测当前帖子的顶级父类别ID:

function get_top_level_cat_id ($catid) {
while ($catid) {
$cat = get_category($catid);
$catid = $cat->category_parent;
$catParent = $cat->cat_ID;
}
return $catParent;
}

然后将当前的single.php复制到_single.php并将所有single.php内容替换为:

<?php
// functions.php !!!
$category = get_the_category($post->ID);
$catid = $category[0]->cat_ID;
$top_level_cat_id = get_top_level_cat_id ($catid);

if ($top_level_cat_id == XX) {require __DIR__ . '/_single_XXX.php';}
elseif ($top_level_cat_id == YY) {require __DIR__ . '/_single_YYY.php';}
else {require __DIR__ . '/_single.php';}
?>

所以现在我可以将_single.php复制到_single_XXX.php并按照我喜欢的方式进行编辑。 _single_YYY.php,_single_ZZZ.php等也一样。

我仍然对此类解决方案不满意,并希望获得更好的建议。

答案 2 :(得分:0)

您可以在single.php中使用此代码来切换模板,如下所示:

 if ( in_category('fruit') ) {
         include 'single-fruit.php';
     } elseif ( in_category('vegetables') ) {
         include 'single-vegetables.php';
     } else {
         // Continu enter code here with normal Loop
         if ( have_posts() ) : while ( have_posts() ) : the_post();
         // ...
     }
相关问题