Child theme stylesheet loading before the parent theme stylesheet

I was creating a child theme for a wordpress theme. I created style.css file in child theme which overrided some of the parent theme styles and a functions.php file which included the parent style.css as below:


<?php
function theme_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
}
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
?>

Now when I activated the child theme from WordPress admin, changes in the child theme were not reflecting. I checked the browser source code and found that the child style.css was included before the parent style.css.

Adding the parent theme style dependency in child themes functions.php file as shown below resolved the issue but the parent theme style got included twice.


<?php
function theme_enqueue_styles() {
$parent_style = 'parent-style';

wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style )
);
}
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
?>

This was because in parent theme header.php file, the style.css file was directly included using the following line of code in the <head> section instead of enqueuing all styles at the wp_enqueue_scripts action.


<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" media="screen"/>

To resolve the issue I removed the above line from header.php, deleted theĀ  functions.php file from the child theme and added the following code in parent theme functions.php file:


add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );

function theme_enqueue_styles() {

/* If using a child theme, auto-load the parent theme style. */
if ( is_child_theme() ) {
wp_enqueue_style( 'parent-style', trailingslashit( get_template_directory_uri() ) . 'style.css' );
}

/* Always load active theme's style.css. */
wp_enqueue_style( 'style', get_stylesheet_uri() );
}

NOTE: The best practice is to enqueue all your styles (and scripts) at the wp_enqueue_scripts action so that all the linked files load in order of execution.

Leave a Comment

Back to top