4

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

3

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.

0
0

You shouldn't be echoing your CSS styles in the <head>. You should be using wp_enqueue_style()

Add something like this to your functions.php file:

add_action( 'wp_enqueue_scripts', 'wpse_259600_enqueue_scripts' );
function wpse_259600_enqueue_scripts() {
  wp_enqueue_style( 'mytheme-critical', get_template_directory_uri() . '/css/critical.css' );
}
1
  • You cannot use get_template_directory() that way, it needs URL, should be get_template_directory_uri().
    – Scott
    Commented Mar 12, 2017 at 5:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.