Adding custom js and css to a WordPress theme

This theme is based on HTML5 Blank, a powerful starter theme for WordPress. Taking the same approach, we need to create two new functions – one for our scripts and one for our styles – and then hook into the WordPress core to load them in the correct place. Sounds tricky, but it deceptively simple. Here’s what it looks like:

<?php

// Load scripts (header.php)
function load_materialize_js()
{
    if ($GLOBALS['pagenow'] != 'wp-login.php' && !is_admin()) {

    	wp_register_script('materializejs', get_template_directory_uri() . '/js/materialize.min.js', array('jquery'), '1.0.0'); // Materialize
        wp_enqueue_script('materializejs');

        wp_register_script('init', get_template_directory_uri() . '/js/init.js', array('jquery'), '1.0.0'); // Custom JS
        wp_enqueue_script('init');
    }
}


// Load styles
function load_materialize_css()
{
    wp_register_style('materialicons', 'https://fonts.googleapis.com/icon?family=Material+Icons');
    wp_enqueue_style('materialicons');
    
    wp_register_style('materializecss', get_template_directory_uri() . '/css/materialize.min.css', array(), '1.0.0', 'all');
    wp_enqueue_style('materializecss');
    
    wp_register_style('style', get_template_directory_uri() . '/style.css', array(), '1.0', 'all');
    wp_enqueue_style('style');
}



// Add Actions
add_action('init', 'materialize_js'); // Add Custom Scripts to wp_head
add_action('wp_enqueue_scripts', 'materialize_css'); // Add Theme Stylesheet
}

?>
Suggest an edit

If you think this page contains an error or could be improved - or you have a suggestion for a new article, drop me a message!

Spread the love