# Inline Critical CSS From Your Theme

> Prints the contents of a critical.css file from your active theme folder directly in the page head, so above-the-fold content is styled before the main stylesheet finishes loading.

- Type: PHP
- Runs: Frontend only
- Category: [Performance](https://wpide.com/library/category/performance/)
- Tags: css, critical-css, core-web-vitals
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/perf-inline-critical-css/

## Code

```php
// File name inside the active theme folder.
$wpide_critical_file = 'critical.css';

add_action( 'wp_head', function () use ( $wpide_critical_file ) {
    $path = get_stylesheet_directory() . '/' . $wpide_critical_file;

    if ( ! is_readable( $path ) ) {
        return;
    }

    $css = wp_cache_get( 'wpide_critical_css', 'wpide' );

    if ( false === $css ) {
        $css = (string) file_get_contents( $path );
        $css = preg_replace( '#/\*.*?\*/#s', '', $css );
        $css = trim( preg_replace( '/\s+/', ' ', $css ) );
        wp_cache_set( 'wpide_critical_css', $css, 'wpide', HOUR_IN_SECONDS );
    }

    if ( $css ) {
        echo '<style id="wpide-critical-css">' . wp_strip_all_tags( $css ) . "</style>\n";
    }
}, 1 );
```

## Notes

Generate a critical.css file (under 14 KB) with a critical CSS tool and put it in your (child) theme folder; nothing happens until the file exists.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Inline Critical CSS From Your Theme" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
