Loading WordPress theme JavaScript the right way: Enqueue scripts

Instead of adding your theme javascript manually in the header.php/footer.php, a better way is to enqueue the files, so that they are loaded via wp_head() or wp_footer().

Here is how – add the following to your theme’s functions.php:

/*  Enqueue javascript
/* ------------------------------------ */	
function alx_scripts()  
	wp_enqueue_script( 'flexslider', get_template_directory_uri() . '/js/jquery.flexslider.min.js', array( 'jquery' ),'', false );
	wp_enqueue_script( 'scripts', get_template_directory_uri() . '/js/scripts.js', array( 'jquery' ),'', true ); 
	if ( is_singular() && get_option( 'thread_comments' ) )	{ wp_enqueue_script( 'comment-reply' ); }
add_action( 'wp_enqueue_scripts', 'alx_scripts' );  

In this example I am loading flexslider in the header, and a general theme scripts file in footer. So, if you set to true, it will load in the footer.

Read more

Loading WordPress theme CSS the right way: Enqueue styles

We don’t want to add direct links to our style.css and other css files in the header.php – let’s keep it clean there!

Instead, add the following to your theme’s functions.php:

/*  Enqueue css
/* ------------------------------------ */	
function alx_styles() 
	wp_enqueue_style( 'style', get_stylesheet_uri() );
	wp_enqueue_style( 'font-awesome', get_template_directory_uri().'/fonts/font-awesome.min.css' );
add_action( 'wp_enqueue_scripts', 'alx_styles' ); 

In this example, I am loading style.css and a Font Awesome css file that is in the theme’s subfolder named /fonts/.

Note, in order for this to work, your theme must have this inside the header.php < head > tag:

<?php wp_head(); ?>

Function reference: wp_enqueue_style