【问题标题】:Add css-file to single-post-template based on category根据类别将 css 文件添加到单个帖子模板
【发布时间】:2016-02-11 16:33:43
【问题描述】:

我正在使用此功能(在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;' )
      });

【问题讨论】:

  • 请务必注明使用 wp_enqueue_style 时发生的情况。短语“//我尝试包含 css 文件失败”中几乎没有嵌入任何信息。由于尝试执行代码,是否有任何输出记录或可见的堆栈跟踪?您是否尝试过设置日志记录或调试?
  • 对不起,我收到一个 PHP 错误,所以整个页面只是呈现为空白。
  • 谢谢,这是朝着正确方向迈出的一步。如果您可以复制该错误的文本,这对于发布和故障排除过程很有用。您可能必须使用 PHP 日志记录才能弄清楚如何做这类事情,但它会很有用
  • 调试时我得到这个:“解析错误:语法错误,/www/webvol18/td/5azsfnodhbyqngs/utt.se/public_html/wp-content/themes/中的意外'single'(T_STRING) utt.se/functions.php 第 49 行"
  • 我注意到,在您的回答中,if 的返回以分号结尾,而在您的问题中,它以逗号结尾。出于好奇,您原帖的第 49 行是哪一行?

标签: php css wordpress wordpress-theming


【解决方案1】:

我没有为特定模板添加 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' );
        }
    }
}

它回答了问题的第一部分,这对第二部分有帮助吗?

【讨论】:

    【解决方案2】:

    所以,经过一番谷歌搜索后,我实际上找到了一个非常简单的答案:

    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;' )
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-10
      • 2011-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多