Scotts Web Dev Banner
Did you notice... every article on this site has an associated video? Consider subscribing to Scotts Web Dev on YouTube! :)

WordPress: How To Load Stylesheets & Scripts

WordPress is a Content Management System that provides many conventions, functions, filters & more for you to work with and manipulate content.

When using a CMS, it’s essential to play within the rules of that ecosystem.

Never load local or 3rd party scripts or stylesheets using <link> or <script> tags.

Use wp_enqueue_script and wp_enqueue_style instead.

Loading Stylesheets & Scripts In HTML Can Be Problematic

If you’re using a third party library, and that third party library depends on another script (like jquery) to work, how can you be sure that JQuery is available when your script is called?

Well you can make it work, but you see my point.

By taking advantage of WordPress’s built in stylesheet and script handling functions, you can integrate your local styles and scripts into WordPress so that it’s aware of them and can be loaded properly.

Loading WordPress Scripts With wp_enqueue_script Example Code

Here’s a sample call to load slick slider via wp_enqueue_script:

wp_enqueue_script('slick-js', 'https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.9.0/slick.min.js', ['jquery-core'], '1.9.0', true);
  • slick-js: This is the name we chose to give this script. WordPress will append -js to this name, and give this script element an id. Your HTML will end up as <script id=”slick-js-js” …
  • The URL: The cloudflare cdn link is the external link to the resource
  • jquery-core: This is a single element in an array of dependencies that this script relies on. WordPress will ensure that jquery-core is loaded and ready before slick-js.
  • 1.9.0: This is the version number of the script and is used for cache busting purposes. You can user any number you’d like here, but try to keep it like a versioning system.
  • true: This tells wp_enqueue_script to load the javascript in the footer. I often do this for pagespeed purposes and wrap all javascript that uses this file in jQuery(document).ready(){}.

Loading WordPress Stylesheets With wp_enqueue_style Example Code

wp_enqueue_style() is very similar to wp_enqueue_script. The parameters are the same except for the last one. With wp_enqueue_style, the last parameter is the media string (all, print, etc). You can omit it for media=”all”.

wp_enqueue_style('slick-style', 'https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.9.0/slick.min.css', [], '1.9.0');

WordPress Now Handles Your Scripts & Stylesheets

Now, WordPress is aware of your scripts and stylesheets and will load them properly. You can even manipulate them with other functions, actions, and filters.

See more WordPress Tutorials