How to avoid loading style.css twice in child-theme?

I have twentyseventeen child-theme, and I found this code:

add_action( 'wp_enqueue_scripts', 'child_enqueue_styles',99);
function child_enqueue_styles() {
    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
     wp_enqueue_style( 'seventeen-child',get_stylesheet_directory_uri() . '/style.css', array( $parent_style ));
if ( get_stylesheet() !== get_template() ) {
    add_filter( 'pre_update_option_theme_mods_' . get_stylesheet(), function ( $value, $old_value ) {
         update_option( 'theme_mods_' . get_template(), $value );
         return $old_value; // prevent update to child theme mods
    }, 10, 2 );
    add_filter( 'pre_option_theme_mods_' . get_stylesheet(), function ( $default ) {
        return get_option( 'theme_mods_' . get_template(), $default );
    } );


But there is problem that style.css is loading twice. I tried code from Reference Wordpress, but then my overrides files like footer.php, navigation.php from child-theme are not loading.

Could someone help me with it to avoid loading .css twice and keep full functionality?

2 Answers

You usually don’t need to enqueue a child theme’s stylesheet. The parent theme does that. This is a bit confusing, so I’ll explain.

In most themes, Twenty Seventeen included, the stylesheet is loaded like this:

wp_enqueue_style( 'twentyseventeen-style', get_stylesheet_uri() );

The trick to understanding what’s going on here is understanding what get_stylesheet_uri() does. When a regular theme is activated, this function returns the URL to the theme’s style.css file. However, when a child theme is activated, the function returns the URL for the child theme’s style.css file.

This means that when you create a child theme with a style.css file, that file will automatically be enqueued, but the parent theme’s won’t. So all you need to do in your child theme is enqueue the parent theme’s stylesheet:

add_action( 'wp_enqueue_scripts', 'child_enqueue_styles', 9 );
function child_enqueue_styles() {
    wp_enqueue_style( 'parent-style', get_parent_theme_file_uri( 'style.css' ) );

Note that I set the priority to 9. This means that the parent theme’s stylesheet will get enqueued before the child theme’s, which will be enqueued at the default priority of 10.

Leave a Comment