Optimizing dynamically-generated CSS

Last updated 4 days ago


function my_dynamic_styles() {

    $styles = array();

    if ( 1 == get_option( 'option_1', 'default' ) ) {
        $css['body']['color'] = '#333';
    }

    if ( 1 == get_option( 'option_2', 'default' ) ) {
        $css['body']['background'] = '#fff';
    }

    $css['body a']['color'] = get_option( 'option_3', 'default' );

    $css = apply_filters( 'my_custom_css_array_filter', $css );

    $final_css = '';
    foreach ( $css as $style => $style_array ) {
        $final_css .= $style . '{';
        foreach ( $style_array as $property => $value ) {
            $final_css .= $property . ':' . $value . ';';
        }
        $final_css .= '}';
    }

    echo $final_css;
}
add_action( 'wp_head', 'my_dynamic_styles', 99 );

Source: http://aristath.github.io/blog/optimize-inline-css

All code snippets are licensed GPLv2 or later unless otherwise stated.