How to inline the contents of an entire stylesheet with WordPress?

I’m using WordPress, but this question could probably apply to other PHP-driven templating system.

I’d like to have a css file (i.e. critical.css) that contains all the styles for important global elements & above-the-fold content (e.g. typography, header includes, navigation, site-wide banners/heros), kept separate from my modular content, page-specific styles & footer styles. I then want to take the contents of this file and print it between style tags right below the document title tag.

Read More

The goal is to improve above-the-fold rendering speed. I’ve noticed a definite improvement in the rendering of above-the-fold content when those styles are prioritized (along with any resets), even if those improvements are more experiential than technical.

But…I’m having trouble figuring out how to “print” the inline styles from this document into the wp_head.

I’ve explored wp_add_inline_style and this does not seem to offer the functionality I’ll need. It appears you have to define those styles within a function, and that’s definitely not what I’m going after.

  1. Does there exist a method for hooking inline styles taken from my critical.css file into the wp_head? wp_print_styles is either deprecated or not recommended according to the Codex.
  2. If not, what is the preferred method of emphasizing these critical styles in WordPress? Preferably, a method that’s not render-blocking or doesn’t rely on a metabox.

I’m trying to avoid using a PHP include (i.e. dumping everything between PHP tags in a critical-styles.php file and then calling that in the wp_head) in favor of something cleaner or that can be achieved with functions.php or WordPress’s native hooks. With all the emphasis on Pagespeed optimization these days, I was surprised that this hadn’t been asked here in a WordPress context. Any help on this or methods that have worked better for you are greatly appreciated.

Related posts

1 comment

  1. You can simply include the actual CSS file in header.php:

    <style>
        <?php include 'path/to/critical.css'; ?>
    </style>
    

    PHP’s include() function doesn’t require that the included file also has to be PHP.

    Alternatively, if you want to keep things in functions.php, you could do a file_get_contents() and hook into the wp_head action hook:

    function hook_critical_css() {
        $critical_css = file_get_contents( 'path/to/critical.css' );
        echo '<style>' . $critical_css . '</style>';
    }
    add_action('wp_head','hook_critical_css');
    

Comments are closed.