How to Load CSS & JS in WordPress
While converting an HTML page to a WordPress theme, I learned how to properly add Bootstrap, custom styles, and scripts. Here’s what I’ve learned so far.
load_stylesheets() function – Enqueues CSS files for the blog, including Bootstrap, Google Fonts (Lato), and two custom stylesheets (style.css and style2.css).
load_scripts() function – Enqueues JavaScript files, including jQuery and Bootstrap JS, loaded in the footer for better performance.
Both functions hook into WordPress’s wp_enqueue_scripts action to properly load assets.
<?php
function load_stylesheets(){
wp_register_style("bootstrapcss", "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css", array(), '1.0.0', 'all');
wp_enqueue_style( "bootstrapcss" );
wp_register_style("googlefont", "http://fonts.googleapis.com/css?family=Lato", array(), '1.0.0', 'all');
wp_enqueue_style( "googlefont" );
wp_register_style("stylecss", get_template_directory_uri() . "/css/style.css", array(), '1.0.0', 'all');
wp_enqueue_style( "stylecss");
wp_register_style("style2css", get_template_directory_uri() . "/css/style2.css", array(), '1.0.0', 'all');
wp_enqueue_style( "style2css" );
}
add_action( "wp_enqueue_scripts", "load_stylesheets" );
function load_scripts(){
wp_register_script("jqueryjs", "https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js", array(), '1.0.0', true);
wp_enqueue_script( "jqueryjs" );
wp_register_script("bootrstrapjs", "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js", array(), '1.0.0', true);
wp_enqueue_script( "bootrstrapjs" );
}
add_action( "wp_enqueue_scripts", "load_scripts" );
Leave a Reply