Skip to content

WordPress theme Tip01: include CSS and JavaScript files via functions.php

Like and share:

Tip01, involved files: functions.php

The best way to modify a WordPress theme is to not modify it at all 😀 Instead you would modify a child theme that is based on the parent theme of your choice. This will let you receive all future updates and not to lose your changes when updating (WordPress overwrites theme files with every new theme version). The good news - an example of starter child theme is included with my themes!

If you were dealing with child themes before, most likely you are including the parent theme's CSS file via style.css. That is the standard way of doing it, so you might be surprised why Tiny Forge and Tiny Framework child themes do it the other way.

WordPress Codex writes about this:

The child theme’s stylesheet will overwrite the parent theme’s stylesheet, but chances are you want to include the parent theme's stylesheet. To do this, you need to start the stylesheet with the following line:

@import url("../twentytwelve/style.css");

This line must go after the header code and before any other CSS rules. If you put other CSS rules before the @import, it will not work.

Although it is the easiest way to include the parent theme’s stylesheet, but it's not the best. The best way to include additional CSS and JavaScript files is using functions.php file.

/**
 * Custom Child Theme functions.
 *
 * Tip01 - Properly include additional CSS and JavaScript files via functions.php.
 */
function tinyframeworkchild_scripts_styles() {

	// Adding CSS file of the Parent theme.
	wp_register_style( 'tinyframework-style',
	get_template_directory_uri() . '/style.css',
	array(),
	'2.0.4',
	'all' );

	// Adding CSS file of the Child theme. This style sheet stands last so it would override parent theme and other stylesheets.
	wp_register_style( 'tinyframeworkchild-style',
	get_stylesheet_uri(),
	array(),
	'2.0.4',
	'all' );

	// Enqueing:
	wp_enqueue_style( 'tinyframework-style' );
	wp_enqueue_style( 'tinyframeworkchild-style' );

	// Below is an example how to enqueue the script.

	wp_enqueue_script( 'your-script-name',
	get_stylesheet_directory_uri() . '/js/your-script-file-name.js',
	array(),
	'2.0.4',
	true ); //placed before body close tag
}
add_action( 'wp_enqueue_scripts', 'tinyframeworkchild_scripts_styles' );

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *