php - 根据类别将 css 文件添加到单后模板

标签 php css wordpress wordpress-theming

我正在使用此函数(在 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/

相关文章:

php - INI文件到PHP中的多维数组

php - MySql 从两个相同的表中获取一条记录并进行检查

javascript - 如何通过 JavaScript 应用 CSS3 转换?

php - 查询不给出空记录

jquery - 网站完全加载后显示菜单项

php - 转换为 MyISAM, `foreign_key_checks = 0` 不工作

php - 如何在MYSQL列中过滤写入的消息?

html - 具有 100% 高度 DIV 的 Joomla 页脚中间

javascript - 根据选择值隐藏 jQuery 中的元素

php - WordPress 一页上多个查询错误