How to properly insert a stylesheet in wp_head

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?

Leave a Comment