Wordpress Customizer 内联 css 到 css 文件

Wordpress Customizer inline css to css file

我正忙于 WordPress 的定制程序,它工作正常我只在样式标签(内联)中获得 css 的输出,我希望它在 customizer.css 文件中。

有人知道如何将 CSS 添加到 customizer.css 中吗?

<?php
    function customizerCSS() {
        wp_enqueue_style('custom-style', get_template_directory_uri() . '/customizer.css');

        $color = fw_get_db_customizer_option('body_background');

        $custom_css = '
                html, body {
                        background-color : ' . $color . ';
                }';
        wp_add_inline_style('custom-style', $custom_css );
    }
    add_action( 'wp_enqueue_scripts', 'customizerCSS' );
 ?>

您可以使用 file_get_contents for getting all css written in the customizer.css file and file_put_contents 将新的 css rules 添加到 customizer.css 文件中。

您的代码将是:

function customizerCSS() {
    $color = fw_get_db_customizer_option('body_background');

    $custom_css = '
                html, body {
                        background-color : ' . $color . ';
                }';

    $file = file_get_contents(TEMPLATEPATH.'/customizer.css');

    if (strpos($file, $custom_css) === false) { // for not rewriting file every time, when there is no changes
        $file .= $custom_css;
        file_put_contents(TEMPLATEPATH.'/customizer.css', $file);
    }

    wp_enqueue_style('custom-style', get_template_directory_uri() . '/customizer.css');
}
add_action( 'wp_enqueue_scripts', 'customizerCSS' );

我们正在从 $custom_css 获取所有新的 css rules,从 customizer.css 获取所有内容并进行比较。如果 $custom_css 中有新的 css rulescustomizer.css 样式表中不存在,那么我们只需将它们写入文件即可。

编辑:

下面的函数每次都会用 $custom_css 变量的值覆盖 customizer.css 文件:

function customizerCSS() {
    $color = fw_get_db_customizer_option('body_background');

    $custom_css = '
                html, body {
                        background-color : ' . $color . ';
                }';

    file_put_contents(TEMPLATEPATH.'/customizer.css', $custom_css);

    wp_enqueue_style('custom-style', get_template_directory_uri() . '/customizer.css');
}
add_action( 'wp_enqueue_scripts', 'customizerCSS' );