我使用这个函数(在function.php
中)为特定类别的 slug 添加模板,但是我也希望使用特定的 css 文件,但是我不知道如何将其正确嵌入过滤器中。我在下面尝试过,但这只会呈现一个空白页(所以php错误),感谢任何帮助:
原始代码,允许在 Function.php 中创建帖子类别的模板(即"单类别名称.php"):
add_filter('single_template', create_function(
'$the_template',
'foreach( (array) get_the_category() as $cat ) {
if ( file_exists(TEMPLATEPATH . "/single-{$cat->slug}.php") )
return TEMPLATEPATH . "/single-{$cat->slug}.php";
}
return $the_template;' )
);
我试图包含外部 css 的失败尝试:
add_filter('single_template', create_function(
'$the_template',
'foreach( (array) get_the_category() as $cat ) {
if ( file_exists(TEMPLATEPATH . "/single-{$cat->slug}.php") )
return TEMPLATEPATH . "/single-{$cat->slug}.php",
//my code:
wp_enqueue_style( 'single-{$cat->slug}', get_template_directory_uri() . '/css/single-{$cat->slug}.css', array(), '1.1', 'all');
}
return $the_template;' )
});
我没有为特定模板添加 CSS,所以我从我自己的一个项目(简化)和 is_page_template 函数中混合了以下内容。
add_action('wp_enqueue_scripts', 'mcd_theme_styles');
if( !function_exists("mcd_theme_styles") ) {
function mcd_theme_styles() {
wp_register_style( 'some-css', get_template_directory_uri() . '/assets/dist/css/some-css.css', array(), '1.4', 'all' );
if ( is_page_template( 'templates/about.php' ) ) {
wp_enqueue_style( 'some-css' );
}
if ( is_singular() ) {
wp_enqueue_style( 'different-css' );
}
}
}
它回答了问题的第一部分,这对第二部分有帮助吗?
所以,经过一番谷歌搜索,我实际上找到了一个非常简单的答案:
add_filter('single_template', create_function(
'$the_template',
'foreach( (array) get_the_category() as $cat ) {
if ( file_exists(TEMPLATEPATH . "/single-{$cat->slug}.php") )
return TEMPLATEPATH . "/single-{$cat->slug}.php";
return STYLESHEETPATH . "css/single-{$cat->slug}.css";
}
return $the_template;' )
);