1

I've noticed that when I load the CSS for a child theme in the way shown here: https://digwp.com/2016/01/include-styles-child-theme/, I get double entries in the chrome inspector for my CSS rules, and have to disable the second set shown in order to change to first set (by checking/unchecking the rules for example).

This is using the code below:

function example_enqueue_styles() {

    // enqueue parent styles
    wp_enqueue_style('parent-theme', get_template_directory_uri() .'/style.css');

    // enqueue child styles
    wp_enqueue_style('child-theme', get_stylesheet_directory_uri() .'/style.css', array('parent-theme'));

}
add_action('wp_enqueue_scripts', 'example_enqueue_styles');

However, I found a different version here on this forum that seems to only load the CSS once, as I would wish:

function use_parent_theme_stylesheet() {
    // Use the parent theme's stylesheet
    return get_template_directory_uri() . '/style.css';
}

function my_theme_styles() {
    $themeVersion = wp_get_theme()->get('Version');

    // Enqueue our style.css with our own version
    wp_enqueue_style('child-theme-style', get_stylesheet_directory_uri() . '/style.css',
        array(), $themeVersion);
}

// Filter get_stylesheet_uri() to return the parent theme's stylesheet 
add_filter('stylesheet_uri', 'use_parent_theme_stylesheet');

// Enqueue this theme's scripts and styles (after parent theme)
add_action('wp_enqueue_scripts', 'my_theme_styles', 20);

Could someone please explain why the second version works properly and first one repeats the rules?

Also I notice that the version in the codex also seems to behave like the first one. Link here:https://codex.wordpress.org/Child_Themes#How_to_Create_a_Child_Theme

I'm confused - is the version that loads the custom rules twice doing something wrong? It certainly seems like that, but then it's listed as an "official version" (i.e it's in the codex).

1 Answer 1

1

There's nothing wrong with css rules ending up in your inspector twice. In many cases you want the first version, loading both parent and child styles. After all, in that case your child style sheet only needs to have the styles you want different from the parent. The browser will correctly apply the child rule if they're both there. If the parent theme style sheet is not there and the child theme style sheet is incomplete, your theme will break.

The second version you give indeed only loads the child style sheet. The filter makes sure that if the theme asks for something from the style directory (like an icon or a secondary stylesheet), it is retrieved from the parent directory. If you use the second version, make sure you copy the complete parent style.css and adapt that one.

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.