单个帖子类别使用父类别模板

时间:2012-05-05 作者:Pollux Khafra

我在我的子主题中的一个文件夹中有一个标记为“single”的帖子模板。我需要子类别使用与其父类别相同的模板。我读过十几本教程,都有三年多的历史了,似乎已经不管用了。那么正确的方法是什么呢?这就是我所尝试的。

function pa_category_top_parent_id ($catid) {
 while ($catid) {
  $cat = get_category($catid); // get the object for the catid
  $catid = $cat->category_parent; // assign parent ID (if exists) to $catid
  // the while loop will continue whilst there is a $catid
  // when there is no longer a parent $catid will be NULL so we can assign our $catParent
  $catParent = $cat->cat_ID;
}
return $catParent;
}
define(SINGLE_PATH, STYLESHEETPATH . \'/single\');
/**
* Filter the single_template with our custom function
*/
add_filter(\'single_template\', \'my_single_template\');
/**
* Single template function which will choose our template
*/
function my_single_template($single) {
 global $wp_query, $post;
 foreach((array)get_the_category() as $cat) :
    $categoriapadre= pa_category_top_parent_id ($cat);
    if(file_exists(SINGLE_PATH . \'/single-cat-\' . $cat->slug . \'.php\'))
    return SINGLE_PATH . \'/single-cat-\' . $cat->slug . \'.php\';
    elseif(file_exists(SINGLE_PATH . \'/single-cat-\' . $categoriapadre . \'.php\'))
    return SINGLE_PATH . \'/single-cat-\' . $categoriapadre . \'.php\';

  endforeach;
 return $single;
}

1 个回复
最合适的回答,由SO网友:Wyck 整理而成

您应该尝试使用WordPress hierarchy 而不是singe-cat-.

使用创建父类别模板category.phpcategory-{slug}.php , 然后使用这里的技术,http://codex.wordpress.org/User:MichaelH/MyPlugins.

或者,要获得更多选项,请尝试此插件,http://wordpress.org/extend/plugins/category-template-hierarchy/

结束