Here’s how I load scripts and styles in WordPress themes, in functions.php.
function load_scripts() { // load styles wp_enqueue_style( 'custom-css-1', get_stylesheet_directory_uri() . '/css/custom-css-1.css' ); wp_enqueue_style( 'my-secret-script-css', get_stylesheet_directory_uri() . '/css/my-secret-script.css' ); // load javascript wp_enqueue_script( 'my-secret-script', get_stylesheet_directory_uri() . '/js/my-secret-script.js' ); } add_action( 'wp_enqueue_scripts', 'load_scripts' );
The above code would load up two css files, custom-css-1.css
and my-secret-script.css
. It would also load one JavaScript file, my-secret-javascript.js
.
This post by Brian Krogsgard at WPCandy describes the proper way of loading scripts, using wp_register_script
, as it takes dependencies into consideration and allows loading of scripts by their defined name. However, I think the wp_register_script
methodology is lengthier and a bit more difficult to read, mostly due to the dependency stuff.
However, you do need to take dependencies into consideration if you’re using a JavaScript library, like jQuery.
wp_register_style
should also be used to load styles with dependencies. This article at Tuts+ has a very good description and examples on loading CSS stylesheets using wp_register_style
and wp_enqueue_style
.
You should also be aware of the differences when authoring themes and plugins, which Brian also explains in his post on WPCandy. That mostly involves one WordPress function out for another.
Let me know if you run into any issues, comments are open!
Well, now what?
Work with Me
I'm available for hire and always taking new clients, big and small. Got a project or an idea you'd like to discuss? Startup plan but no developer to make it happen? Just get in touch, I'd love to see if I can help you out!
Leave some Feedback
Got a question or some updated information releavant to this post? Please, leave a comment! The comments are a great way to get help, I read them all and reply to nearly every comment. Let's talk. 😀
Longren.io is proudly hosted by DigitalOcean
