Enqueue Css and Js

Building the WordPress theme is one of the tedious things for the new developer not for who have intense eagerness to learn theme developing. During developing the new theme, we must have basic knowledge about hooking the stylesheet and JavaScript(Enqueue Css and Jss).  WordPress has its own customizing style to write the code so, developer must know about the basic concept of WordPress. Therefore, theme should run without incompatibility issue.

 

Including styles and scripts is arguably simple process. The theme folder must have function.php file to enqueue styles and scripts.  Literally, I am going to explain about three methods to adding CSS and Js in WordPress theme.

 

Enqueuing Styles and Scripts

As I said earlier, proper way to add styles & scripts to theme is to enqueue theme in functions.php. Style.css file should have included in your theme folder to active theme and enqueue the style in proper manner.

 

  1. First Method

 

Enqueue the Stylesheets:  wp_enqueue_style() 
wp_enqueue_style( 'style', get_stylesheet_uri() ); 

is the query to include main stylesheet to WordPress theme.  This enqueue automatically run the style.css file in theme.  Therefore, if you wanted to load a stylesheet name called ‘bootstrap.css’ in a folder names ‘CSS’ in your theme`s root directory:

wp_enqueue_style( 'bootstrap', get_template_directory_uri() . '/css/bootstrap.css',false,'1.1','all');

 

Enqueue the Scripts:

                wp_enqueue_script()

So, if you wanted to load a script named “bootstrap.js” in a folder named “JS” in your theme’s root directory, you would use:

wp_enqueue_script( ‘bootstrap’, get_template_directory_uri() . ‘/js/bootstrap.js’, array ( ‘jquery’ ), 1.1, true);

 

Combining Stylesheet and JavaScript

To increase standard and readability, best to combine all enqueued styles and scripts into a single function.

function Custom_theme_scripts() {
wp_enqueue_style( 'style', get_stylesheet_uri() );
wp_enqueue_style( 'bootstrap', get_template_directory_uri() . '/css/ bootstrap.css', array(),         '1.1', 'all');
wp_enqueue_script( ' bootstrap ', get_template_directory_uri() . '/js/ bootstrap.js', array (          'jquery' ), 1.1, true); }
add_action( 'wp_enqueue_scripts', 'Custom_theme_scripts' );

 

  1. Second Method

Enqueue the Stylesheets

Include before closing the head Tag.

<link type="text/css" rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/css/bootstrap.css">

Enqueue the Scripts

Include before closing body Tag.

<script src="<?php echo get_template_directory_uri(); ?>/js/bootstrap.js"></script>

 

  1. Third Method

Similar to 2 method use stylesheet before closing head tag and scripts before closing body tag.

 

Enqueue Stylesheet

<link href="<?php echo home_url(); ?>/wp-content/themes/custom-theme-name/css/bootstrap.css" rel="stylesheet">

 

Enqueue Scripts

<script src="<?php echo home_url(); ?>/wp-content/themes/custom-theme-name/js/bootstrap.min.js"></script>