我知道这是一个老问题,但如果其他人在搜索同一主题时发现,请注意不要在WordPress主题中使用include语句。始终使用get_template_part() 或locate_template() 相反
(参见http://make.wordpress.org/themes/guidelines/guidelines-theme-check/)
以下代码使用WordPress过滤器完成任务,并将自动搜索任何和所有类别的模板:
/**
* Replace "themeslug" with your theme\'s unique slug
*
* @see http://codex.wordpress.org/Theme_Review#Guidelines
*/
add_filter( \'single_template\', \'themeslug_single_template\' );
/**
* Add category considerations to the templates WordPress uses for single posts
*
* @global obj $post The default WordPress post object. Used so we have an ID for get_post_type()
* @param string $template The currently located template from get_single_template()
* @return string The new locate_template() result
*/
function themeslug_single_template( $template ) {
global $post;
$categories = get_the_category();
if ( ! $categories )
return $template; // no need to continue if there are no categories
$post_type = get_post_type( $post->ID );
$templates = array();
foreach ( $categories as $category ) {
$templates[] = "single-{$post_type}-{$category->slug}.php";
$templates[] = "single-{$post_type}-{$category->term_id}.php";
}
// remember the default templates
$templates[] = "single-{$post_type}.php";
$templates[] = \'single.php\';
$templates[] = \'index.php\';
/**
* Let WordPress figure out if the templates exist or not.
*
* @see http://codex.wordpress.org/Function_Reference/locate_template
*/
return locate_template( $templates );
}
代码中有几个弱点。首先,这意味着WordPress对单个帖子执行两次locate\\u template()(一次在该函数运行之前,一次在运行期间)。第二,我不认为有一个干净的方法来确定优先查找哪些类别。这意味着,如果您的帖子位于多个类别中,并且具有唯一的单个帖子模板,那么您将无法选择使用哪个模板。