If you are a designer or a developer then knowing the proper way to enqueue scripts and stylesheets in your WordPress themes and plugins is very important. Because if you don’t do it proper way then you will probably run the risk of conflicting with other themes and plugins, and potentially creating problems that could have been easily avoided.
WordPress has a built-in function wp_enqueue_script to enqueue scripts and stylesheets for making sure that everything works properly. This function provides a systematic way of loading JavaScripts and styles in WordPress themes and plugins. And without any doubt, it is the best way because it allows everyone to utilize the built-in JavaScript libraries instead of loading the same third-party plugin scripts multiple times.
If you haven’t really used wp_enqueue_script function before, it can be little confusing. So here we will show you how to properly enqueue scripts and stylesheets into your WordPress themes and plugins.
Following code snippet displays how to enqueue scripts and stylesheets in our theme the proper way.
// enqueue scripts and stylesheets to wordpress
function wcs_enqueue_scripts() {
// enqueue jQuery
wp_enqueue_script('jquery');
// enqueue Google fonts Open Sans and Neucha
wp_register_style( 'google-fonts', 'http://fonts.googleapis.com/css?family=Open+Sans|Neucha', false, NULL, 'all' );
wp_enqueue_style( 'google-fonts');
// enqueue our custom scripts
wp_register_script( 'custom-scripts', get_template_directory_uri() . '/js/custom.scripts.js', array('jquery'), NULL, true );
wp_enqueue_script( 'custom-scripts' );
// enqueue our theme's style.css
wp_register_style( 'theme-style', get_template_directory_uri() . '/style.css', false, NULL, 'all' );
wp_enqueue_style( 'theme-style' );
// enqueue our custom css file
wp_register_style( 'custom-css', get_template_directory_uri() . '/css/custom.style.css', false, NULL, 'screen' );
wp_enqueue_style( 'custom-css' );
}
add_action( 'wp_enqueue_scripts', 'wcs_enqueue_scripts' );