WORDPRESS - include CSS in functions.php doesnt work

Viewed 1043

I need to include some external css files, i use this snippet in functions.php but neither of them works.. Why..?

    add_action( 'wp_enqueue_scripts', 'add_css' );

function add_css() {
    wp_enqueue_style( 'parent-style', get_template_directory_uri().'/style.css' );
    wp_enqueue_style( 'style', get_template_directory_uri().'/assets/css/bootstrap.css' );
}

I'm using Twenty-Twenty-One child theme This is my style.css

/*Theme Name: Twenty Twenty-One Child
    Theme URI: https://wordpress.org/themes/twentytwentyone/
    Template: twentytwentyone
    Author: the WordPress team
    Author URI: https://wordpress.org/
    */
h2{
    color:red!important;
} */

h2 is to see if it works.

2 Answers

If you're using a child theme, you want to use get_stylesheet_directory_uri() instead of get_template_directory_uri - Unless the stylesheets are part of the parent theme.

function add_css() {
    wp_enqueue_style( 'parent-style', get_stylesheet_directory_uri().'/style.css' );
    wp_enqueue_style( 'style', get_stylesheet_directory_uri().'/assets/css/bootstrap.css' );
}

Depending on how your parent theme loads it's styles your function will vary. You can check the Enqueue stylesheet section in the Theme handbook for more clarification. Below is their example if the parent theme loads its style using a function starting with get_stylesheet

Make sure you are using the correct parent handle, 'parent-style' is used for TwentyFifteen theme for example.

add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
function my_theme_enqueue_styles() {
    $parenthandle = 'parent-style'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme.
    $theme = wp_get_theme();
    wp_enqueue_style( $parenthandle, get_template_directory_uri() . '/style.css', 
        array(),  // if the parent theme code has a dependency, copy it to here
        $theme->parent()->get('Version')
    );
    wp_enqueue_style( 'child-style', get_stylesheet_uri(),
        array( $parenthandle ),
        $theme->get('Version') // this only works if you have Version in the style header
    );
}

You should also look at the wp_enqueue_style code reference as the handle for your bootstrap style should probably not be style as it needs to be unique e.g. bootstrap-style

Related