How to properly insert a stylesheet in wp_head

I am generating critical CSS for every page and category. At the moment I am inserting the stylesheet through functions.php like this simply using echo.

function criticalCSS_wp_head() {
  if (is_front_page() ){
    echo '<style>';
    include get_stylesheet_directory() . '/css/critical/ccss-index.min.css';
    echo '</style>';    
  }
  elseif (is_category('orange') ){
    echo '<style>';
    include get_stylesheet_directory() . '/css/critical/ccss-orange.min.css';
    echo '</style>';    
  }
  elseif (is_page('hello-world') ){
    echo '<style>';
    include get_stylesheet_directory() . '/css/critical/ccss-hello-world.min.css';
    echo '</style>';    
  }
  elseif (is_single() ){
    echo '<style>';
    include get_stylesheet_directory() . '/css/critical/ccss-single.min.css';
    echo '</style>';    
  }
}
add_action( 'wp_head', 'criticalCSS_wp_head' );
  1. What would be the best way to include these stylesheets with regards to best practise coding style and pure relentless speed, meaning to avoid PHP calls, database calls and so on.
  2. Is it better to directly hard-code the critical CSS in the page template perhaps like written in this post (#10) linked from the official WordPress Optimization documentation?

edit
Since this question was answered I forgot to mention that critical CSS needs to be inline in the DOM and not being linked to as a file to avoid render blocking. So I am still looking for a way to use the critical CSS with wp_enqueue_scripts. Perhaps store the file content in a variable and output that when wp_enqueue_scripts asks for it?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can do it like this, put it in your functions.php :

This is the correct way of doing it “the WordPress way”.

<?php
    // Check if function exisits
    if (!function_exists('rg_templateScriptSetup')) {
         // if not, create one
         function rg_templateScriptSetup() {
             // Register styles in WordPress
             wp_register_style('prefix-basic-css', get_template_directory_uri(). '/css/basic-style.css');

             // Register styles in WordPress
             wp_register_style('first-css', get_template_directory_uri(). '/css/first-style.css');

             // Register styles in WordPress
             wp_register_style('second-css', get_template_directory_uri(). '/css/second-style.css');

        if (is_page('your_page_name') {
            // enqueue your first style
            wp_enqueue_style('first-css');
        } else if(is_page('your_other_page_name')) {
            // enqueue your second style
            wp_enqueue_style('second-css');
        } etc...


    } // End of Stylesheet logic / setup

    add_action('wp_enqueue_scripts', 'rg_templateScriptSetup');

?>

Why?

Because WordPress gives you all the tools, necessary to achieve that goal.

What is exactly happening here:

  1. first, we check if the function already exists
  2. if it doesn’t, we create our function
  3. then we “register our styles”, basically telling WordPress: here,grab these CSS’, so.. WordPress has our stylesheets in it’s pocket, but it doesn’t use them yet
  4. then we use the native WordPress function is_page in combination with an if
    statement (if (is_page(‘your-page-name’))
  5. in case that if statement returns bool ‘true’ we activate the css according to our condition (in your case, the page name).

I hope that helps.

In case that answer has helped you, please mark it as correct, and not just grab the code, thanks.

Personal question: what do you mean by critical? Lots of !important?

Method 2

The best-practice and generally accepted right way to add CSS or JS is to enqueue them. That way, if you have say a theme + 2 plugins that all want to enqueue jQuery, you only end up with 1 copy loaded – not 3.

In functions.php:

add_action('wp_enqueue_scripts', 'my_enqueues');
function my_enqueues() {
    if(is_front_page()) {
        wp_enqueue_style('front-page', get_stylesheet_directory() . '/css/critical/ccss-index.min.css', array(), '', 'screen');
    } elseif(is_category('orange')) {
        wp_enqueue_style('orange', get_stylesheet_directory() . '/css/critical/ccss-orange.min.css', array(), '', 'screen');
    }
}

If your per-page styles are short, you can actually enqueue inline styles instead so that the web browser isn’t requesting a separate resource.

add_action('wp_enqueue_scripts', 'my_inline_enqueues');
function my_inline_enqueues() {
    wp_add_inline_style('front-page',
        '.myfrontpageclass { font-size:6em; }'
    );
}

Final suggestion – I don’t know the content of your stylesheets, but I’d suggest that it may be both simpler and faster to load these pages if you just include all of the CSS in the theme’s style.css file together. Use body_class to target whatever you need to and keep it all in one minified file.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x