我正在使用此函数(在 function.php
中)为特定类别 slug 添加模板,但我也希望使用特定的 css 文件,但我不知道如何嵌入它正确地在过滤器中。我在下面尝试过,但这只会呈现一个空白页面(所以 php-error),感谢您的帮助:
原始代码,可以在 Function.php 中创建帖子类别的模板(即“single-categoryname.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' );
}
}
}
它回答了问题的第一部分,对第二部分有帮助吗?
关于php - 根据类别将 css 文件添加到单后模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35319110/