How to Properly Add Scripts and Stylesheets in your Wordpress theme

Check out my other posts and tutorials on Web Development!

Simple Script and Style Enqueuing

The proper way to load scripts and stylesheets in your WordPress theme is to place the wp_enqueue_scripts hook in your theme’s functions.php file.

if (!is_admin()) add_action( 'wp_enqueue_scripts', 'add_my_theme_styles' );
if (!is_admin()) add_action( 'wp_enqueue_scripts', 'add_my_theme_scripts' );

function add_my_theme_styles() {
	wp_enqueue_style( 'my-stylesheet',  get_stylesheet_directory_uri() . '/path/to/stylesheet.css' ); 

function add_my_theme_scripts() {
    // script will load in footer - change third parameter to false to load in head
	wp_enqueue_script( 'my-js',  get_stylesheet_directory_uri() . '/path/to/script.js', true );

Expanding on This

Sometimes you may want to load a certain script or stylesheet only on a particular page. In such a case, we can register the script or stylesheet and load it later inside a conditional statement. Below we are registering a script and stylesheet in which we will only load on our custom page template.

if (!is_admin()) add_action( 'wp_enqueue_scripts', 'add_page_template_scripts_and_styles' );

function add_page_template_scripts_and_styles() {
	wp_register_style( 'my-stylesheet',  get_stylesheet_directory_uri() . '/path/to/stylesheet.css' ); 
	wp_register_script( 'my-js',  get_stylesheet_directory_uri() . '/path/to/script.js', true );

    if ( is_page_template( 'page-my_page_template.php' ) ) { 
		    wp_enqueue_style( 'my-stylesheet' );
		    wp_enqueue_script( 'my-js' );

Loading jQuery

WordPress comes with jQuery included and will load it automatically if you declare it as a dependency for any of your scripts (more on this below). That said, there is a better way. See my post on a better way to load jQuery in your WordPress theme here.

Loading jQuery Dependent Scripts

For scripts that need jQuery to work, we want declare jquery as a dependency for the script to ensure it won’t load without it. The code below will accomplish just that.

if (!is_admin()) add_action( 'wp_enqueue_scripts', 'add_my_jquery_script' );

function add_my_jquery_script() {
    // script will load in footer
	wp_enqueue_script( 'my-js',  get_stylesheet_directory_uri() . '/path/to/script.js', array('jquery'), true );

Leave a Reply

Contact Us


Subscribe to our blog to receive latest news and tutorials on Web Design, Development, SEO, and more!