How to fix the error “file_get_contents was found in the file functions.php”?

I am building a wordpress theme, I reach the step of finalization.

Right now, I am struggling to fix an error raised by Theme Check, :

file_get_contents was found in the file functions.php File operations
should use the WP_Filesystem methods instead of direct PHP filesystem
calls.

Here the code:

function theme_critical() {
  $critical_css = file_get_contents( get_template_directory() . '/css/critical.css');
  echo '<style>' . $critical_css . '</style>';
}

Basicaly, this code take the content of a CSS file, to print it in the header. This is a critical css.

I searched, but I could not find a way to use WP_filesystem to simply to the same thing than file_get_content does.

Is anyone already faced this issue?

Thanks.

2 Answers
2

To Add External Atylesheet:

Generally speaking, you should use the wp_enqueue_style() function to add external stylesheet to your theme.

function wpse259600_add_style() {
    wp_enqueue_style( 'theme_critical', get_template_directory_uri() . '/css/critical.css', array(), '1.0.0' );
}
add_action( 'wp_enqueue_scripts', 'wpse259600_add_style' );

To Add Internal Stylesheet:

However, if (for whatever reason) you have to add internal stylesheet (i.e. printing the entire CSS file within the HTML <head> tag using the <style> tag), then you may use inclue_once like below:

add_action( 'wp_head', 'wpse259600_internal_css_print' );
function wpse259600_internal_css_print() {
    echo '<style type="text/css">';
    // this will also allow you to use PHP to create dynamic css rules
    include_once get_template_directory() . '/css/critical.css';
    echo '</style>';
}

This will not generate warning in theme check. Although, I wouldn’t recommend this. If you want to add custom CSS this way, you better save it to the database with customizer theme options and then add it with wp_add_inline_style function along with your theme’s main CSS file.

Leave a Comment