我在我的子主题中的一个文件夹中有一个标记为“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;
}