首页 文章

使用Wordpress页面作为样式表?

提问于
浏览
0

我通过在后端使用Page而不是默认的 style.css 文件来编写CSS . 我似乎在弄清楚自己 .

我在Multisite上使用WordPress版本4.7.2 . 我希望CSS在主题激活时生成,因此使用Page .

如果这是一个简单的解决方案并且可以通过其他方式实现此目的,我会提前道歉 . 谢谢!

1 回答

  • 0

    我强烈建议使用插件,例如https://wordpress.org/plugins/wp-add-custom-css/或使用WordPress Customizer "Additional CSS"字段 .

    但是,要回答你的问题,这很简单,因为我修改了一些方法,我用ajax加载了一些页面 . 您需要创建一个页面模板,并且需要FTP和代码编辑器来创建页面,然后将其推送到您的主题文件夹(希望在升级时儿童主题或此模板将消失) .

    我命名了我的CSS页面模板: css-page.php

    它只需要打开php标签 .

    模板css-page.php的代码

    <?php
    
    /**
    *
    * Template Name: CSS page
    * Not a recommended idea.
    *
    */
    
    header("Content-type: text/css; charset: UTF-8");
    
    ob_start("compress");
    
    //minify CSS
    function compress( $minify ) {
    
        /* remove comments */
        $minify = preg_replace( '!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $minify );
    
        /* remove tabs, spaces, newlines, etc. */
        $minify = str_replace( array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $minify );
    
            return $minify;
    }
    
    //get the content
    if (have_posts()) : 
    
    while ( have_posts() ) : the_post();
    
        $content = get_the_content();
    
        $content = wp_filter_nohtml_kses( $content );
    
        echo $content;
    
    endwhile;
    
    endif; 
    
    ob_end_flush();
    

    然后在您的子主题中的functions.php文件中(或者包含该文件或自定义插件)粘贴在以下内容中,将其更改为:

    将值p ='3134'更改为您正在使用此模板的页面ID . 将id =“something”更改为其他内容或将其删除 . 有用于拥有js操作的id或类 .

    For functions.php

    //Get CSS page contents
    function myprefix_page_css() {
        echo '<link rel="stylesheet" id="something" href="'. site_url() .'/?p=3134" type="text/css" media="screen">';
    }
    add_action( 'wp_head', 'myprefix_page_css', 99 );
    

相关问题