Child Theme - Fix for proper stylesheet enqueueing

I didn't notice this until of recent but there are some optimizations we should change to the child theme's functions.php as it relates to loading stylesheets.

1) By default, WordPress automatically includes the style.css file of a theme or child theme if it exists.

You'll notice on every child theme using betheme's current functions.php the style sheet gets loaded twice, one under the handle 'style' which is done by WordPress and higher up in the order loaded into the page's <head> section (because wp uses default priority of 10) and one under the handle 'mfn-child-style' which is done by the child theme functions.php loaded much further down in the page's <head> section (because the function in the child theme's functions.php uses a priority of 101)

At first one would think to simply comment out line 35:
//wp_enqueue_style( 'mfn-child-style', get_stylesheet_directory_uri() .'/style.css' );

This is great and fixes the issue of 2 versions of the same style sheet loading but it loads before most of the other betheme styles and doesn't override much.

The next idea would be to change the instance handle like this:
wp_enqueue_style( 'style', get_stylesheet_directory_uri() .'/style.css' ); //this should override/update the previous 'style' handle registered

Actually, WordPress would ignore this altogether since 'style' has already been registered by the core...however...

If we do both of the following we've fixed all problems:
wp_dequeue_style( 'style' ); //remove wp's auto inclusion of style.css
wp_enqueue_style( 'style', get_stylesheet_directory_uri() .'/style.css' );

First we are dequeueing the automatic WordPress version and then loading our style.css exclusively from our child theme's functions.php while retaining it's priority level of 101 and the style.css loads after all other style sheets.

2) The current child theme's functions.php also loads the parent theme's style.css file but fails due to it using the same handle as the child theme's style.css on line 27.  Go ahead, inspect the code, the parent style sheet is never there.

Regardless of fixing the first problem, we're going to have a conflict and this file never loads because the handle it is using.
wp_enqueue_style( 'style', get_template_directory_uri() .'/style.css' ); //this never loads because the handle 'style' is already registered in our child theme

All we need to do is change the handle and problem fixed:
wp_enqueue_style( 'betheme-parent-style', get_template_directory_uri() .'/style.css' ); //this is a unique handle so it registers properly

However, we probably just want to comment it out altogether because the parent theme style.css is empty and it's unlikely when we are using a child theme that we will ever need this file.
//wp_enqueue_style( 'betheme-parent-style', get_template_directory_uri() .'/style.css' ); //we don't need to load this

Example file:

Comments

Sign In or Register to comment.