WordPress Theme Development Part 7 – Enqueue Scripts and Styles

WordPress developers run WordPress themes and several plugins in a same place. So there are chances to conflict with styles or scripts. WordPress have Enqueue system for solve this problem and adding CSS and Js files perfectly.

Here is sample of Enqueueing files. Add this code to your functions.php.


function travel_enqueue_files() {
	
	wp_enqueue_style( 'slider', get_template_directory_uri() . '/css/slider.css' );

	wp_enqueue_script( 'owl-carousel', get_template_directory_uri() . '/js/owl.carousel.js', array( 'jquery' ) );
	wp_enqueue_script( 'theme-scripts', get_template_directory_uri() . '/js/website-scripts.js', array( 'owl-carousel', 'jquery' ), '1.0', true );
}

add_action( 'wp_enqueue_scripts', 'travel_enqueue_files' );

wp_enqueue_style() functions uses for adding styles file and wp_enqueue_script() for adding scripts. get_template_directory_uri() function brings the folder location for each file.

I’m adding all these enqueue script and style files into an action hook ‘wp_enqueue_scripts’. 

Important thing

Enqueue system only run if you added wp_head() and wp_footer() functions in your header and footer file. Please check Part 5 for how to add these functions properly.

After added your styles and scripts file refresh your website and check if everything working fine. If you face any problem then press Ctrl + U and check is there any mistakes on file names or file paths.

Display All Images

If you enqueue done then you can see all the CSS and Js working fine but still one thing remaining from your HTML template. That is images.
For linking all your images use this function get_template_directory_uri()

Here is a sample how it works


<img src="<?php echo get_template_directory_uri(); ?>/images/travel.jpg" alt=""/>

Hope everything looks like your original HTML file. Thanks !!

Leave a Reply

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