Search code examples
phpcsswordpressinline

Wordpress Customizer inline css to css file


I am busy with the Customizer from WordPress and that is working fine i only getting the output of the css in the style tags (inline) and i want it in the customizer.css file.

Does somebody know how i can add the CSS into the 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' );
 ?>

Solution

  • You can use file_get_contents for getting all css written in the customizer.css file and file_put_contents for adding new css rules into customizer.css file.

    Your code will be:

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

    We are getting all new css rules from $custom_css, everything from customizer.css and comparing them. If there is new css rules in the $custom_css which aren't exists in the customizer.css stylesheet, then we just writе them into file.

    Edit:

    Function below will override customizer.css file with values from $custom_css variable every time:

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