How to Include JavaScript and CSS in Your WordPress Themes and Plugins

How to Include JavaScript and CSS in Your WordPress Themes and Plugins

Knowing the proper way to include JavaScript and CSS files in your WordPress themes and plugins is very important for designers and developers. If you don’t adhere to best practices, you run the risk of conflicting with other themes and plugins, and potentially creating problems that could have been easily avoided. This article is intended as a reference for playing nicely with others.


Best Practices Make Everyone Happy

If you’ve ever developed a theme or plugin for WordPress, or worked with one that someone else has created, you’ve probably come across several different methods for including JavaScript and CSS. While there are several methods that may appear to work in a specific set of circumstances, there is one primary method recommended in the WordPress Codex. This preferred way will ensure your theme or plugin works in all cases, assuming others also code the correct way.

There’s also some misunderstanding about what exactly the Codex says about this, which I will help clarify.


What’s in the Box?

When you download WordPress, a selection of common JavaScript libraries are already included that you can use for your JavaScript development. A list of included libraries can be found in the WordPress Codex wp_enqueue_script article.

All those libraries are included, but by default WordPress only loads the ones it needs to, and only when it needs them in the admin. If you write JavaScript that utilises one of these libraries, you need to tell WordPress that your script needs the library loaded first.


Telling WordPress About Your Script and What It Needs

Some of the things to think about when you’re coding JavaScript for WordPress are:

  • Is there an included library I can use?
  • Can I use the version that’s included?
  • Do I need to load my script in the front-end and in the admin?
  • Which front-end and admin pages do I need to load my script on?

Answering these questions helps you know what you need to do to register and load your script. This is done using a WordPress function called wp_register_script, and here is its usage according to the WordPress Codex:

wp_register_script( $handle, $src, $deps, $ver, $in_footer );

So what are these variables and do we need them every time? (This is covered on the Codex page, so I’ll be brief and use plain English)

  • $handle – what you’ll use to refer to this particular script wherever you might need to enqueue it, and you have to include this variable at the very least
  • $src – the path to the source file within your plugin or theme
  • $deps – an array containing the $handle for any other scripts your script needs to run (i.e. a dependency)
  • $ver – the version number for your script, which can be used for cache-busting. By default, WordPress will use its own version number as the version number for your script
  • $in_footer – do you want your script to load in the footer? Set this to true or false. It is false by default, so it loads in the header where wp_head() is, and if you specify true it will load where wp_footer() appears in the theme

What Is “Cache-Busting”?

Browsers remember what scripts and stylesheets they’ve downloaded for a particular site based on the URL of the script and stylesheet. If you change the URL, even just by adding a querystring, the browser assumes it’s a new file and downloads it.


Ok, So Let’s Try Some Examples

Here is the most basic example for loading a custom script:

function wptuts_scripts_basic()
{
	// Register the script like this for a plugin:
	wp_register_script( 'custom-script', plugins_url( '/js/custom-script.js', __FILE__ ) );
	// or
	// Register the script like this for a theme:
	wp_register_script( 'custom-script', get_template_directory_uri() . '/js/custom-script.js' );

	// For either a plugin or a theme, you can then enqueue the script:
	wp_enqueue_script( 'custom-script' );
}
add_action( 'wp_enqueue_scripts', 'wptuts_scripts_basic' );

First, we register the script, so WordPress knows what we’re talking about. The way to find the path for our JavaScript file is different whether we’re coding a plugin or a theme, so I’ve included examples of both above. Then we queue it up to be added into the HTML for the page when it’s generated, by default in the <head> where the wp_head() is in the theme.

The output we get from that basic example is:

<script type="text/javascript" src="http://yourdomain.com/wp-content/plugins/yourplugin/js/custom-script.js?ver=3.3.1"></script>

Now if your script relies on one of the libraries included with WordPress, like jQuery, you can make a very simple change to the code:

function wptuts_scripts_with_jquery()
{
	// Register the script like this for a plugin:
	wp_register_script( 'custom-script', plugins_url( '/js/custom-script.js', __FILE__ ), array( 'jquery' ) );
	// or
	// Register the script like this for a theme:
	wp_register_script( 'custom-script', get_template_directory_uri() . '/js/custom-script.js', array( 'jquery' ) );

	// For either a plugin or a theme, you can then enqueue the script:
	wp_enqueue_script( 'custom-script' );
}
add_action( 'wp_enqueue_scripts', 'wptuts_scripts_with_jquery' );

Note: By default, jQuery is loaded with noConflict to prevent clashes with other libraries (such as Prototype). See the noConflict section of the Codex if you don’t know how to deal with that.

See what I did there? You just add an array with the ‘jquery’ handle as a dependency. It uses an array here, because your script could have multiple dependencies. If your script uses jQuery and jQuery UI, you’d add jQuery UI to your dependency array, like array( 'jquery', 'jquery-ui-core' )

So now the output has changed, and we can see that jQuery has also been added into the <head> of the page:

<script type='text/javascript' src='http://yourdomain.com/wp-includes/js/jquery/jquery.js?ver=1.7.1'></script>
<script type='text/javascript' src='http://yourdomain.com/wp-content/plugins/yourplugin/js/custom-script.js?ver=3.3.1'></script>

Let’s try an example with all the bells and whistles:

function wptuts_scripts_with_the_lot()
{
	// Register the script like this for a plugin:
	wp_register_script( 'custom-script', plugins_url( '/js/custom-script.js', __FILE__ ), array( 'jquery', 'jquery-ui-core' ), '20120208', true );
	// or
	// Register the script like this for a theme:
	wp_register_script( 'custom-script', get_template_directory_uri() . '/js/custom-script.js', array( 'jquery', 'jquery-ui-core' ), '20120208', true );

	// For either a plugin or a theme, you can then enqueue the script:
	wp_enqueue_script( 'custom-script' );
}
add_action( 'wp_enqueue_scripts', 'wptuts_scripts_with_the_lot' );

Ok, so I’ve now added a version and specified that this script needs to be loaded in the footer. For the version number, I’ve chosen to use today’s date because it’s easy to keep track of, but you can use any version numbering you like. The output for this one is slightly different too, jQuery is output in the <head> and our script along with jQuery UI is output just before </body>, like this:

<head>
...
<script type='text/javascript' src='http://yourdomain.com/wp-includes/js/jquery/jquery.js?ver=1.7.1'></script>
...
</head>
<body>
...
<script type='text/javascript' src='http://yourdomain.com/wp-includes/js/jquery/ui/jquery.ui.core.min.js?ver=1.8.16'></script>
<script type='text/javascript' src='http://yourdomain.com/wp-content/plugins/yourplugin/js/custom-script.js?ver=20120208'></script>
</body>

Getting Your Priorities Straight

Some people may prefer not to use the proper enqueuing methods because they feel they have less control over the order in which scripts are loaded. For example, in a theme that uses modernizr, the theme author might want to make sure modernizr is loaded early on.

Something I haven’t mentioned earlier is more detail on how the add_action function works, as this is where we can exercise a little influence over the order of things. Here’s the usage of the function according to the WordPress Codex page:

add_action( $tag, $function_to_add, $priority, $accepted_args );

Note that often, and up until now in this article, only the $tag and $function_to_add parameters are used. The $priority parameter defaults to 10, and the $accepted_args parameter defaults to 1. If we want our scripts or styles to be enqueued earlier, we simply lower the value for $priority from the default. For example:

function wptuts_scripts_important()
{
	// Register the script like this for a plugin:
	wp_register_script( 'custom-script', plugins_url( '/js/custom-script.js', __FILE__ ) );
	// or
	// Register the script like this for a theme:
	wp_register_script( 'custom-script', get_template_directory_uri() . '/js/custom-script.js' );

	// For either a plugin or a theme, you can then enqueue the script:
	wp_enqueue_script( 'custom-script' );
}
add_action( 'wp_enqueue_scripts', 'wptuts_scripts_important', 5 );

The output will be the same as we’ve seen previously, but it will occur earlier in the HTML document.


Overriding Default Libraries and Using Content Delivery Networks

There may be times when you want to use a different version of a library that’s included with WordPress. Perhaps you want to use a cutting-edge version or you don’t want to wait for the next release of WordPress before using the latest stable version of jQuery. Another reason might be that you want to take advantage of Google’s CDN version of a library.

It’s important to note that this should only be done on plugins or themes used on sites that you will be personally maintaining. Any plugins or themes that you release for public use should use the libraries included with WordPress.

“Why?!”, I hear you ask. For the simple reason that you don’t control those sites. You don’t know what other plugins and themes might be used there, and you don’t know how often they will update your plugin or theme. Using the libraries packaged with WordPress is the safest option.

Having said that, if you are wanting to do this on a site you control, here’s how it’s done:

function wptuts_scripts_load_cdn()
{
	// Deregister the included library
	wp_deregister_script( 'jquery' );
	
	// Register the library again from Google's CDN
	wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js', array(), null, false );
	
	// Register the script like this for a plugin:
	wp_register_script( 'custom-script', plugins_url( '/js/custom-script.js', __FILE__ ), array( 'jquery' ) );
	// or
	// Register the script like this for a theme:
	wp_register_script( 'custom-script', get_template_directory_uri() . '/js/custom-script.js', array( 'jquery' ) );

	// For either a plugin or a theme, you can then enqueue the script:
	wp_enqueue_script( 'custom-script' );
}
add_action( 'wp_enqueue_scripts', 'wptuts_scripts_load_cdn' );

So first of all, I deregister the included version of the library, otherwise conflicts between different versions could be introduced. Then register the alternate version, using the same handle, and I’ve chosen to specify null as the version (it’s already in the URL!) and specified not in the footer. The rest of our code is the same, because we were depending on whatever script used the ‘jquery’ handle. The output we get now looks like:

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script type='text/javascript' src='http://yourdomain.com/wp-content/plugins/yourplugin/js/custom-script.js?ver=3.3.1'></script>

Note: One of the reasons this is a bad idea to do in a plugin or theme for public release, is that all other plugins and themes used on this site will now have to use this version of jQuery. Also, the newly registered version of jQuery doesn’t have noConflict set, so if any other plugin or theme scripts use Prototype for example, this will break things.


Don’t Be Greedy

So far we haven’t mentioned anything about how to do all this in the admin, only on the front-end. The primary difference is what action to use. Instead of add_action( 'wp_enqueue_scripts', 'wptuts_scripts_basic' ); which we use for the front-end, the action for the admin is add_action( 'admin_enqueue_scripts', 'wptuts_scripts_basic' );

Something that’s important to do for both the front-end and admin is be selective about which pages you load your scripts on. If your plugin or theme has a script that only does something on one front-end or admin page, such as the theme’s options page, or maybe a page with a specific widget, you only need to load your script on that page. No point clogging things up and loading scripts on pages where they’re not being used!

There’s a great example in the WordPress Codex on how to load scripts only on plugin pages. Because plugins and themes can vary a lot in how they’re written, I won’t go into specifics here on how to be choosy about which pages you load scripts on, but it was important to mention so you’re aware of it when you’re coding.


That’s Scripts, Now Styles

The process for styles is almost exactly the same as the process for scripts. It is done using a WordPress function called wp_register_style, and here is its usage according to the WordPress Codex:

wp_register_style( $handle, $src, $deps, $ver, $media );

Note that the only difference there between wp_register_script and wp_register_style is that instead of an $in_footer parameter, we have a $media parameter. This parameter can be set to any of the following: 'all', 'screen', 'handheld', and 'print', or any other W3C recognised media type.

So an example of how you might enqueue a style would be:

function wptuts_styles_with_the_lot()
{
	// Register the style like this for a plugin:
	wp_register_style( 'custom-style', plugins_url( '/css/custom-style.css', __FILE__ ), array(), '20120208', 'all' );
	// or
	// Register the style like this for a theme:
	wp_register_style( 'custom-style', get_template_directory_uri() . '/css/custom-style.css', array(), '20120208', 'all' );

	// For either a plugin or a theme, you can then enqueue the style:
	wp_enqueue_style( 'custom-style' );
}
add_action( 'wp_enqueue_scripts', 'wptuts_styles_with_the_lot' );

This is a fairly comprehensive example, utilising most of the parameters, and the output it produces looks like:

<link rel='stylesheet' id='custom-style-css'  href='http://yourdomain.com/wp-content/plugins/yourplugin/css/custom-style.css?ver=20120208' type='text/css' media='all' />

So, Why Doesn’t Everyone Already Do Things This Way?

Good question, and the other question I guess you might ask is, “What makes you think this is the ‘right’ way and not just your preference?”. Essentially the answer is that this is the approach recommended by WordPress. It ensures that any combination of plugins and themes should be able to work together happily and without doubling up.

I’ve seen a few themes and frameworks around the place that use <script></script> and <link /> tags in their header.php, and even footer.php, files to load the scripts and styles for the theme itself. There’s really no reason to do things this way. As I’ve demonstrated above, it’s perfectly possible to prioritise scripts and styles and nominate whether they load in the header or footer from the comfort and safety of your functions.php. The benefit being that your theme / framework will work with a wider range of other plugins / child themes.

One example was loading jQuery using the <script></script> tags, which might appear to work nicely, but this can actually cause jQuery to be loaded twice! Loading jQuery in this way will not stop WordPress from loading its version of jQuery for other plugins, as WordPress’ version is in noConflict mode by default, and a plugin may specify it as a dependancy. So now you’ll have jQuery working for both noConflict mode and $, and also probably break any plugin that uses the Prototype library.


Conclusion

WordPress is a fantastic system, and it has been developed with a lot of thought. If there’s a mechanism made available to do something, it’s often a good idea to use it. When developing your plugins and themes, try to remember to code thoughtfully and for playing nicely with others.

What do you think about the use of wp_enqueue_script and its associated functions and actions? Do you know of any examples where it’s being done incorrectly? Do you know of any reason not to follow the advice above?

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Martin

    I am a little curious on how to do the following using wp_enqueue_script(). Just in case jQuery won’t load…

    window.jQuery || document.write(‘<script src="/inc/js/libs/jquery.min.js”>\x3C/script>’)

    • Martin

      <script src=”http://code.jquery.com/jquery-1.7.1.min.js”></script>
      <script>window.jQuery || document.write(‘<script src=”<?php echo get_template_directory_uri(); ?>/inc/js/libs/jquery.min.js”>\x3C/script>’)</script>

  • http://webdesignergeeks.com Ajay Patel

    When i was starting to create wordpress plugin and themes, this is one of my confusing task.
    How i can include my plugin js & css?

    BTW really nice and helpful article.

  • Pingback: How to Include JavaScript and CSS in Your WordPress Themes and … - EtondeGroup Blog of Web Applications | EtondeGroup Blog of Web Applications

  • http://www.themesquare.com/ Bharat

    Awesome, I tried this in thesis theme to create a custom jquery slider, it works fine for me. Will follow these tips when creating my new WP plugin. Thank you.

  • http://themble.com/bones Eddie

    Great Article. Very detailed and easy to understand.

    I don’t think I’ll change my calls in Bones though.

    The whole jQuery setup in WordPress is broken IMO. I don’t think plugins should call jQuery at all since the majority of themes call it by default. This always leads to it being loaded more than once. Add that to the fact that the output of wp_head is compressed and tough to easily scan, jQuery is often loaded two sometimes three times depending on the plugins used.

    I know for plugin authors who’s plugin relies on jQuery, it’s vital to include it, but honestly when’s the last time you worked with a theme that didn’t load jQuery by default?

    I’ve found that by keeping my call outside wp_head, I can check wp_head and remove any instance of jQuery I find. It’s definitely a matter of personal preference, and to each their own, but I find it makes my life easier.

    • http://wp.envato.com/ Japh Thomson
      Author

      Hi Eddie, thanks for your thoughts and your kind words. It sounds like you’re currently forced to do things the way you are by the way other developers are coding.

      In an ideal world, all plugin developers would use wp_register_script() as shown above, listing jQuery as a dependency. Then jQuery only gets included once.

      If you used wp_enqueue_script() in Bones to enqueue jQuery, then any other plugin that registered a script depending on jQuery would have what it needed, and jQuery would only get loaded once.

      I guess that’s not how it’s worked out in your experience, which is a shame. I guess the decision then is, do we code for an ideal world in the hopes that it brings us closer to it?

      I’m sure there are people following your example simply because you do it that way, but it’s not clear immediately that you also remove the enqueued jQuery or other instances of jQuery that might get injected into wp_head().

      • http://themble.com/bones Eddie

        Good point. Ideally, we should be coding out sites “the right way” since that’s really the best way to promote best practices as a whole.

        When I find a duplicate jQuery call in wp_head I always go in and deregister it, but that does require some homework.

        I honestly do see the benefits of enqueuing and perhaps it’s just my anal retentiveness with having clean code that’s preventing me from doing it.

        Articles like these will help the community, as sometimes clearing things up for people who didn’t fully understand how enqueuing worked (me), will help the cause.

        • http://wp.envato.com/ Japh Thomson
          Author

          I certainly hope this article can help clear this things up for people.

          I would be interested to know if you tried switching Bones to use wp_enqueue_script(), what that would look like and if it was solve problems or create them.

          To me, it seems you’re currently making more work for yourself, and creating potential for conflicts. It’s my “anal retentiveness” about clean code that makes me long to see Bones using wp_enqueue_script() ;)

          • http://www.roberttilt.name Robert Tilt

            I’m a great lover of Bones, and have been using it as a base since I found it. I’m keen to fork a version to add enqueue functionality though!

          • http://wp.envato.com/ Japh Thomson
            Author

            Hey Robert, I forked the responsive version of Bones on GitHub and Eddie has now pulled my changes into the main repository! :)

  • http://roadha.us haliphax

    Does wp_register_style work on the back-end dashboard yet? I remember in previous versions, you had to use a hacky workaround to get a stylesheet on the administration side (which I am still using in one of my plugins).

    • http://wp.envato.com/ Japh Thomson
      Author

      Hi Haliphax, I believe the way to do it would be:

      function wptuts_load_admin_scripts_and_styles()
      {
          // Register and enqueue scripts and styles here
      }
      add_action( "admin_enqueue_scripts", "wptuts_load_admin_scripts_and_styles" );
      
      • http://roadha.us haliphax

        Ah, nice… yep; looks like it’s been in the core since 2.8. Thanks for the pointer!

        • http://wp.envato.com/ Japh Thomson
          Author

          My pleasure! :)

  • Pingback: How to Include JavaScript and CSS in Your WordPress Themes and Plugins | Shadowtek | Hosting and Design Solutions

  • http://www.binarymoon.co.uk/ Ben

    Interesting article. I’ve been using wp_enqueue_script for ages so that’s not new to me, but the idea of registering the script first is.

    Is there a reason/ advantage to use wp_register_script before enqueing it – as opposed to just using wp_enqueue_script (which has all the register script functionality)?

    • http://wp.envato.com/ Japh Thomson
      Author

      Hi Ben, my immediate thought would be that registering separately allows you to easily register all necessary scripts in a single function when your plugin is loaded. Sort of like declaring variables / constants.

      Then enqueuing them only in the functions or pages where they are actually needed.

      There may be other reasons, but that’s what springs to mind.

  • http://sevenspark.com Chris

    It’s important to note that this should only be done on plugins or themes used on sites that you will be personally maintaining. Any plugins or themes that you release for public use should use the libraries included with WordPress.

    THANK YOU for pointing this out. I try to explain this to other developers constantly, and they rarely listen. It’s so important to use the default library included in the core to ensure compatibility. WordPress is a modular system, and everyone needs to share the same resources :)

  • http://tommcfarlin.com Tom McFarlin

    Japh – thanks for posting this. Definitely a practice more developers should be adopting!

    • http://wp.envato.com/ Japh Thomson
      Author

      Hey Tom, my pleasure! :)

  • http://kg69design.com kg69design

    Very usefull article. Many thanks!
    It would be great if all aspects of wordpress described in such detail and clarity.

  • http://unrelatedmedia.ca Neil Davidson

    Very nice article. I had to scan it twice to make sure you mentioned wp_deregister_script( ‘jquery’ );

    This is such an important function because of all the plugins that call javascript libraries. By removing any trace calls to a library first you ensure that the one you load with wp_enqueue_script() is the only copy. It’s amazing how many theme developers don’t add this simple bit and have duplicate script libraries.

    • http://wp.envato.com/ Japh Thomson
      Author

      Hi Neil, quite right, if you’re going to load an included library from somewhere else, it’s very important to deregister the existing one. Although, I would say 9 times out of 10, if it’s already there you might as well just use it ;)

  • Amanda

    Great tut, thanks. There’s a typo in your codes for themes though:
    wp_register_style( ‘custom-style’, get_template_directory_uri() . ‘css/custom-style.css’, array(), ’20120208′, ‘all’ );

    There should be another forward slash in front of the folder name if your style is in a sub-folder. Same for the JS examples:

    wp_register_style( ‘custom-style’, get_template_directory_uri() . ‘/css/custom-style.css’, array(), ’20120208′, ‘all’ );

    • http://wp.envato.com/ Japh Thomson
      Author

      Well spotted, Amanda, thanks for that! All fixed now :)

  • Dan

    Great article very well explained Japh. I’d like to know how would I go about inserting scripts conditionally cause in my theme I have a lot of if checks to place diferent scripts depending on the page.

    For Ex:

    <script src="/js/slider.js”>
    ?>

    Thanks.

    • http://wp.envato.com/ Japh Thomson
      Author

      Thanks, Dan! :)

      I’m not sure if your code example came through correctly, but if I’m understanding you, then you might do something like the following:

      function wptuts_conditional_scripts()
      {
          wp_register_script( 'custom-script-1', plugins_url( '/js/custom-script-1.js', __FILE__ ) );
          wp_register_script( 'custom-script-2', plugins_url( '/js/custom-script-2.js', __FILE__ ) );
      
          if ( get_option( 'condition_one', false ) == true )
          {
              wp_enqueue_script( 'custom-script-1' );
          }
          else
          {
              wp_enqueue_script( 'custom-script-2' );
          }
      }
      add_action( 'wp_enqueue_scripts', 'wptuts_conditional_scripts' );
      

      That’s just one example though, and perhaps it wouldn’t be appropriate to register all the scripts in all cases. You might include the ‘register’ line above the ‘enqueue’ line instead.

      Does that help?

      • Dan

        Yes I missed the pre tags, I think I understand how to do what I want now

        So following your example I would:

        function wptuts_conditional_scripts()
        {
        wp_register_script( ‘custom-script-1′, plugins_url( ‘/js/custom-script-1.js’, __FILE__ ) );

        if ( is_page_template(‘portfolio.php) )
        {
        wp_enqueue_script( ‘custom-script-1′ );
        }

        }
        add_action( ‘wp_enqueue_scripts’, ‘wptuts_conditional_scripts’ );

        Maybe the register and enqueue function should both be run inside the if checks?

        Another qustion, If I have fancybox which consist of a facybox.js and a fancybox.css and the css file must come before the fancybox.js, I have to create two functions one for registering the script and another for the css. Are the priorities respected between the add_action for the script and the style or should I register the css first and then pass the css as a dependency $deps on the script registering?

        And one last, I’m sorry but I want to have this clear, I sometimes have a lot of scripts on my themes, Do I have to create a function for each script or I can place several scripts if they are related inside one function? If so the order in which they register is respected as priority? Thank you for clearing my doubts.

        • http://wp.envato.com/ Japh Thomson
          Author

          Hi Dan, basically you can have a function that registers all your styles and scripts, and then you enqueue them where you need them (keeping in mind that anything enqueued after the header will be inserted in wp_footer()).

          You can register or enqueue as many styles and scripts as you need in a single function (providing that makes sense for your purposes.

          Also, styles are inserted before scripts, so you should be fine for the fancybox CSS and JS.

          I hope that answers everything! :)

  • http://www.dhechler.com David Hechler

    Just in case you are using this tutorial with a child theme, use this code.

    wp_register_style( ‘custom-style’, get_stylesheet_directory() . ‘/css/custom-style.css’, array(), ’20120208′, ‘all’ );

    instead of

    wp_register_style( ‘custom-style’, get_template_directory_uri() . ‘/css/custom-style.css’, array(), ’20120208′, ‘all’ );

    to get the child theme directory instead of the parent template directory.

    • http://wp.envato.com/ Japh Thomson
      Author

      Hi David, thanks for your comment.

      Are you certain about that? According to the WordPress Codex, get_template_directory() will return the URI for either the theme or child theme, so should work fine. Also, according to the codex, get_stylesheet_directory() returns a filepath not a URI, so wouldn’t work at all.

      • http://wpconsult.net Paul

        he’s right, use wp_get_stylesheet_directory_uri() with child themes

        Also, according to Nacin – core developer, scripts AND styles should use the same hooks
        http://wpdevel.wordpress.com/2011/12/12/use-wp_enqueue_scripts-not-wp_print_styles-to-enqueue-scripts-and-styles-for-the-frontend/

        so not sure where you got the wp_print_styles from.

        • http://wp.envato.com/ Japh Thomson
          Author

          Thanks, Paul! I should’ve looked further, the code David recommends for child theme usage should be:

          wp_register_style( ‘custom-style’, get_stylesheet_directory_uri() . ‘/css/custom-style.css’, array(), ’20120208′, ‘all’ ); // Note the addition of "_uri" too
          

          Also, I got the “wp_print_styles” from the wp_register_styles codex page. Looks like Nacin hasn’t updated the codex yet. I will update the article though, as the wpdevel post is more in line with what I had anticipated finding in the codex!

          Thanks guys :)

        • http://wp.envato.com/ Japh Thomson
          Author

          I’ve just updated the codex page for wp_register_style() too, so now we’re all on the same page

  • http://labcoatmedia.com Paul Lumsdaine

    Excellent tutorial. You explained this very well and i appreciate the quick follow-up you have done with people commenting.

    Thats it, only praise, no questions.

    • http://wp.envato.com/ Japh Thomson
      Author

      Thanks, Paul! Glad you liked the tutorial!

      If you do have any questions later, feel free ;)

  • Pingback: Web Design Weekly #31 | Web Design Weekly

  • Nikolay

    Bookmarked. Thanks for the great article!

  • http://www.tristarwebdesign.co.uk/ Paul Weston

    I am new to WordPress and have just started to learn and use it in my design. I love articles like this one because they give me a guide and a head start to what I should be doing when working with WordPress. I thought this was a great article and one that I will looking at again and again to make sure I get off on the right foot and do things correctly. Thanks for the post.

    • http://wp.envato.com/ Japh Thomson
      Author

      Thanks for your kind words, Paul! I’m really glad you liked the article, and I hope it can continue to be useful for you :)

  • Pingback: ASO Weekly Digest, February 13-17 | Web Hosting Blog at ASO

  • http://www.planetauz.com Auz

    Hi, great tutorial, but I am a little stumped as to why I can’t get the scripts and styles to work for me. This is the code I have at the top of my PLUGIN. The plugin works, but the necessary scripts and styles are not running. Thanks for your help!

    function nextgentn3_activate($atts){
    add_action( ‘wp_enqueue_scripts’, ‘load_tn3_scripts’ );

    extract(shortcode_atts(array(“gid” => ’1′), $atts));

    return nextgentn3($gid);
    }

    function load_tn3_scripts() {
    // Register the script like this for a plugin:
    wp_register_script( ‘jquerytn3′, WP_PLUGIN_URL.”/js/jquery.tn3lite.min.js”);
    wp_register_script( ‘jquerytn3.init’, WP_PLUGIN_URL.”/js/tn3-initialize.js”);

    //register the stylesheet for a plugin:
    wp_register_style( ‘custom-style’, WP_PLUGIN_URL.’/skins/tn3/tn3.css’, array(), ’20120208′, ‘all’ );

    // For either a plugin or a theme, you can then enqueue the script:
    wp_enqueue_script(“jquerytn3″);
    wp_enqueue_script(“jquerytn3.init”);

    wp_enqueue_style( ‘custom-style’ );
    }

    • http://wp.envato.com/ Japh Thomson
      Author

      Hi Auz, sorry but I can’t be 100% sure what’s going wrong from the snippet you’ve provided. Is your plugin available anywhere?

      • http://www.planetauz.com Auz

        @Japh – No, I can’t fully call it a plugin bc I can’t figure out why the scripts and the style sheet are not being pulled in. This is the header of the one and only main PHP file of the plugin. When I hardcode the scripts and the stylesheet into the themes header it works fine. Hmmmmmm… Let me know if you have any other suggestions. Thanks!

      • http://www.planetauz.com Auz

        So I ended up scrapping that version and went this route:

        add_action( ‘wp_enqueue_scripts’, ‘load_tn3_scripts’ );
        add_shortcode(“nextgentn3″, “nextgentn3_activate”);

        function nextgentn3_activate($atts){

        extract(shortcode_atts(array(“gid” => ’1′), $atts));
        return nextgentn3($gid);
        }

        function load_tn3_scripts() {

        /* Register our script. */
        wp_register_script( ‘jquery151′,’http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js’);
        /* Register our script. */
        wp_register_script( ‘jquerytn3′, plugins_url(‘/js/jquery.tn3lite.min.js’, __FILE__) );

        /* Register our script. */
        wp_register_script( ‘jquerytn3.init’, plugins_url(‘/js/tn3-initialize.js’, __FILE__) );

        wp_enqueue_script( ‘jquery151′ );
        wp_enqueue_script( ‘jquerytn3′ );
        wp_enqueue_script( ‘jquerytn3.init’ );

        /* Register our stylesheet. */
        wp_register_style( ‘myPluginStylesheet’, plugins_url(‘/skins/tn3/tn3.css’, __FILE__) );
        wp_enqueue_style( ‘myPluginStylesheet’ );
        }

        … and it WORKS!

  • Johnny

    Do you know if there is a way to register a script and still have it show only on a specified post type. I’ve got two scripts that utilize the jquery library but is only present on a custom post type. In the interest of site efficiency, it would be a waste of resources to include them on other pages when it’s not being used. Same goes for the excluding registered scripts on particular areas of the site.

    • Johnny

      Sorry, I didn’t see it until after I posted but it looks like Dan had the same question.

    • http://wp.envato.com/ Japh Thomson
      Author

      Hi Johnny, I’ve answered Dan above, and also see the link in the article to the Codex page that demonstrates loading scripts only on plugin pages. Hope that helps!

  • http://johncobb.name John

    I was just tinkering with my own personal WP theme that I use for my personal builds and wondering if it was good practice, or worthwhile even, to wrap my enqueued JS (custom scripts, poly-fills, feature detects, etc.) in a simple if( !is_admin() ) check to prevent them from being included in the admin section – just to minimise the chance of conflict on the admin side of WP.

    It would also seem useful to do this if I’m switching out the included jQuery library for the Google CDN version, so therefore the admin section would still use the default library included with that version of WordPress.

    Any thoughts on this?

    By the way, great article Japh – you clearly put a lot of time in to making this as thorough as possible, but also ensuring it was clear and concise! Hope to see more articles like this soon!

    • http://wp.envato.com/ Japh Thomson
      Author

      Hey John! It is absolutely a good practice to use an if( !is_admin() ) { } to limit where your scripts are being loaded.

      As I noted to Johnny above, it’s also good practice to be even more specific about where you load your scripts, especially with plugins, so they’re only loaded on pages where they’re needed.

      Regarding use of the Google CDN version of jQuery, while I don’t personally use it, if you do you should also remember to load it and your own script with high priority to enable noConflict mode. Because WordPress’ default jQuery is loaded this way, so some plugins require it, and also to prevent conflicts with plugins that load Prototype etc. (using multiple libraries on a single site is a whole other discussion though ;))

      I’m glad to hear you enjoyed the article too! Thanks a lot!

  • Pingback: Tweet-Parade (no.7 FEB 2012) | gonzoblog.nl

  • Pingback: WordPress Community Roundup for the Week Ending February 18 - Charleston WordPress User Group

  • Pingback: How to Create a Simple Post Rating System With WordPress and jQuery | Wptuts+

  • Pingback: How to Create a Simple Post Rating System With WordPress and jQuery | Wordpress Webdesigner

  • Pingback: My Stream | How to Create a Simple Post Rating System With WordPress and jQuery | My Stream

  • Pingback: How to Create a Simple Post Rating System With WordPress and jQuery | Shadowtek | Hosting and Design Solutions

  • http://niallm1.com Niall

    Thanks for this article! I’ve really wanted to know how to change over to CDN javascript libraries in WordPress. Do you know if the CDN libraries are cached locally like Google does for it’s sites such as YouTube? I mean the DNS caches are hosted in pretty much every country that Google has a local domain for. Are the CDN’s cached as well or are they all hosted at Google in the US?

  • Pingback: Wordpress Leaks » How to Create a Simple Post Rating System With WordPress and jQuery

  • Pingback: How to Create a Simple Post Rating System With WordPress and jQuery | How to Web

  • Harry

    Hello.

    I’m currently learning to develop a theme on WordPress, and want to include an image carousel (based on jQuery) on the home page of my theme design.

    Firstly, where do I add the wp_register_script and wp_enqueue_script functions? The header.php file? The functions file?

    And as I want the carousel to be just on the home page of my theme, would it be appropriate / best practice to use if (is_page_template (‘home.php’) ), to avoid running the script for other pages.

    Thanks for the article, look forward to your response.

    • http://wp.envato.com/ Japh Thomson
      Author

      Hi Harry! You would add the code to register the scripts in your functions.php file. You could then wrap the enqueuing in an if statement checking is_home().

      For example:

      function wptuts_scripts_basic()
      {
      	// Register the script like this for a theme:
      	wp_register_script( 'custom-script', get_template_directory_uri() . '/js/custom-script.js' );
      
      	if ( is_home() )
      	{
      		// For either a plugin or a theme, you can then enqueue the script:
      		wp_enqueue_script( 'custom-script' );
      	}
      }
      add_action( 'wp_enqueue_scripts', 'wptuts_scripts_basic' );
      
      • Harry

        Thanks for the response Japh.

        I would like to know if this method can work for adding an image carousel to a specific WordPress page, as I have tried but without much luck.

        I’m trying to integrate an infinite carousel (http://www.catchmyfame.com/catchmyfame-jquery-plugins/jquery-infinite-carousel-plugin/) which would extract certain images from the images folder (/wp-content/themes/mytheme/images/) and display them on a page, like the homepage.

        Any thoughts would be helpful.

      • http://themeid.com Emil

        Hi,

        There is no need to register any scripts nor styles. To be honest with you that’s no longer acceptable if you’re submitting Theme to WPROG.

        wp_enqueue_script(‘scripts’, get_template_directory_uri() . ‘/js/scripts.js’, array(‘jquery’), ’1.0.4′, true);

        That’s the proper way of adding JS to WordPress. You can read this in http://wpdevel.wordpress.com/2011/12/12/use-wp_enqueue_scripts-not-wp_print_styles-to-enqueue-scripts-and-styles-for-the-frontend/

        Cheers,
        Emil

        • http://wp.envato.com/ Japh Thomson
          Author

          Hi Emil, thanks for your comment, however I think perhaps you have misinterpreted Andrew’s post and the comments there. If you believe I’ve misinterpreted, can you please quote the specifics that you’re referring to?

  • Pingback: JavaScript・CSSをWordPressテーマやプラグインに適切に組み込む | 備忘録

  • Pingback: Best of WordPress in February 2012 | WP Theme Power

  • Pingback: Best of Tuts+ in February 2012 | Shadowtek | Hosting and Design Solutions

  • Pingback: Best of Tuts+ in February 2012 | How to Web

  • Pingback: Best of Tuts+ in February 2012 | clickshots

  • Pingback: Best of Tuts+ in February 2012 | linuxin.ro

  • Pingback: gmSoft - software factory

  • Pingback: Best of Tuts+ in February 2012 | Wptuts+

  • Pingback: Building a WordPress Security Plugin: The Basics | Wptuts+

  • Pingback: Building a WordPress Security Plugin: The Basics | Wordpress Webdesigner

  • Pingback: My Stream | Building a WordPress Security Plugin: The Basics | My Stream

  • Pingback: Building a WordPress Security Plugin: The Basics | Shadowtek | Hosting and Design Solutions

  • Pingback: Building a WordPress Security Plugin: The Basics | How to Web

  • Pingback: Force Grid View with WP e-Commerce Using Bootstrap | That One Geek

  • Clifford

    How do you turn a script’s embed code into the proper scripting for WordPress (e.g. functions.php, footer.php, both)?

    For example:

    new JotformFeedback({
    formId : “123″,
    buttonText : “Wishbox Form”,
    base : “http://jotform.us/”,
    background : “#F59202″,
    fontColor : “#FFFFFF”,
    buttonSide : “bottom”,
    buttonAlign : “right”,
    type : 2,
    width : 400,
    height : 250,
    instant : true
    });

  • Clifford

    (attempt #2)

    How do you turn a script’s embed code into the proper scripting for WordPress (e.g. functions.php, footer.php, both)?

    For example:

    new JotformFeedback({
    formId : “123″,
    buttonText : “Wishbox Form”,
    base : “http://jotform.us/”,
    background : “#F59202″,
    fontColor : “#FFFFFF”,
    buttonSide : “bottom”,
    buttonAlign : “right”,
    type : 2,
    width : 400,
    height : 250,
    instant : true
    });

  • Clifford

    (attempt #3)
    When the comment board’s ‘pre’ tags fail…

    How do you turn a script’s embed code into the proper scripting for WordPress (e.g. functions.php, footer.php, both)?

    For example:

    http://pastebin.com/aWyQ0s79

    • http://wp.envato.com/ Japh Thomson
      Author

      Hi Clifford, my apologies, I’m not sure how but it seems I missed your comments!

      So as I understand it, you’re wanting to know how, when given a JavaScript code snippet by a third-party service such as JotForm, how should you implement that in a WordPress-y way.

      My suggestion would be to do the following:

      Step 1: Create a JavaScript file in your theme’s js directory called something like jotform-embed.js

      Step 2: Copy and paste the raw JavaScript component into that file, so in the case of your example, that would be this part:

        new JotformFeedback({
           formId		: "123",
           buttonText	: "Wishbox Form",
           base		: "http://jotform.us/",
           background	: "#F59202",
           fontColor	: "#FFFFFF",
           buttonSide	: "bottom",
           buttonAlign	: "right",
           type		: 2,
           width		: 400,
           height		: 250,
           instant		: true
        });
      

      Step 3: Register and enqueue the third-party script and your new embedded script, like so:

      function custom_embed_jotform()
      {
          // Register the script like this for a theme:
          wp_register_script( 'jotform', 'http://jotform.us/min/g=feedback2' );  
          wp_register_script( 'jotform-embed', get_template_directory_uri() . '/js/jotform-embed.js', array( 'jotform' ) );  
      
          // For either a plugin or a theme, you can then enqueue the script:
          wp_enqueue_script( 'jotform-embed' );
      }
      add_action( 'wp_enqueue_scripts', 'custom_embed_jotform' );
      

      Disclaimer: This is off-the-cuff and not tested, but it should work.

      Let me know how you go!

  • Pingback: Developing WordPress Themes Using Responsive Frameworks | Wptuts+

  • Pingback: Developing WordPress Themes Using Responsive Frameworks | Wordpress Webdesigner

  • Pingback: Developing WordPress Themes Using Responsive Frameworks | Shadowtek | Hosting and Design Solutions

  • Pingback: My Stream | Developing WordPress Themes Using Responsive Frameworks | My Stream

  • Pingback: Developing WordPress Themes Using Responsive Frameworks | How to Web

  • Pingback: The header.php - What Needs to Go in It and What Doesn't | Wptuts+

  • Pingback: The header.php – What Needs to Go in It and What Doesn’t | Wordpress Webdesigner

  • Pingback: Header.php – cosa inserire e cosa no | Wordpress Geneus | Sito dedicato a tutorial, training e video su WordPress

  • Pingback: The header.php – What Needs to Go in It and What Doesn’t | Shadowtek | Hosting and Design Solutions

  • Pingback: The header.php – What Needs to Go in It and What Doesn’t | How to Web

  • Pingback: Как создать систему рейтинга записей WordPress на jQuery | Wordpresso

  • Pingback: Sivuston optimointiAndreas Koutsoukos | Andreas Koutsoukos

  • Brian O’Neill

    Thanks for this article. I’m trying to apply what you’ve written to a project I’m working on, but I can’t figure one thing out.

    My theme has a small handful of WordPress plugins as well as a separate jQuery plugin and a “my-scripts” file.

    I want to make sure that “my-scripts” is the last of all scripts to load. I am able to get it to load after the jQuery plugin. But how can I make sure it will load after all of the WordPress plugins?

    Any thoughts are much appreciated!!

    • http://wp.envato.com/ Japh Thomson
      Author

      Hi Brian, I think what you’d want to do here is create another function for enqueuing your final script, and the add_action call for it should have a high priority number (making it lower priority, if that makes sense). For example:

      function wptuts_scripts_last()  
      {  
          // Register the script like this for a theme:  
          wp_register_script( 'custom-script', get_template_directory_uri() . '/js/custom-script.js' );  
        
          // For either a plugin or a theme, you can then enqueue the script:  
          wp_enqueue_script( 'custom-script' );  
      }  
      add_action( 'wp_enqueue_scripts', 'wptuts_scripts_last', 1000 );
      
      • Brian O’Neill

        Thanks so much for getting back to me, Japh!
        I did what you said, and it worked perfectly.
        All the best,
        Brian

  • Anthony

    Thanks for the lesson, man!

    • http://wp.envato.com/ Japh Thomson
      Author

      Hey Anthony, my pleasure! I hope you find it useful

  • Pingback: Image Gallery With Custom Sized Images (Bonus jQuery Plugin) | How to Web

  • Pingback: Image Gallery With Custom Sized Images (Bonus jQuery Plugin) | Wptuts+

  • Pingback: Файл темы header.php — тонкости настройки | Wordpresso

  • Pingback: Создание тем WordPress с помощью адаптивных фреймворков | Неинтересный блог

  • Pingback: Создание тем WordPress с помощью адаптивных фреймворковНеинтересный блог

  • mm

    I’m more clear on how to use the wp_register_script and wp_enqueue_script now. Thanks a bunch.

  • http://www.saganmarketing.com Sergey Sagan

    Thank you for this excellent write up. I’m using this in one of the plugins I’m developing and this helped a lot, especially since you didn’t just show how to do it, but how to do it right. Thanks again!

  • dave

    One obvious reason why people do not do this is because it is significantly more complicated than just added scripts and links to the header manually.

    The fact that a tutorial is needed to explain it, kind of makes that point.

    I prefer to avoid unnecessarily complicated solutions, so unless a site I am building actually experiences one of these conflicts… I go the simple header route. And my clients have appreciated not having to learn function hooks, etc.

    • http://wp.envato.com/ Japh Thomson
      Author

      Hi Dave, thanks for your thoughts! I actually don’t think it’s significantly more complicated at all. It’s slightly different, and maybe fractionally more complicated, but also comes with advantages. Once you know it, you’re golden, so why not learn the correct way to start with? :)

  • Ronald dave

    I Want to add multiple custom javascripts file .And im adding them up in functions.php , but the thing is it loads only one script. HERE’s the code

    function zoomPercent(){
    if (!is_admin()) {
    wp_register_script (‘hide’,
    get_stylesheet_directory_uri().’/js/zoom.js’,
    array(‘jquery’));
    wp_enqueue_script (‘hide’);
    }
    }
    add_action(‘init’,'zoomPercent’);

    function infiniteCarousel(){
    if (!is_admin()) {
    wp_register_script (‘hide’,
    get_stylesheet_directory_uri().’/js/cursoule.js’,
    array(‘jquery’));
    wp_enqueue_script (‘hide’);
    }
    }
    add_action(‘init’,'infiniteCarousel’);

    AND IN THE SOURCE CODE IT GIVES ME THIS

    IT only loads the first javascript not the second . Can you help me out with it ?

    • http://wp.envato.com/ Japh Thomson
      Author

      Hello Ronald, the problem is that you are giving both scripts you are registering the same ‘handle’ of ‘hide’. Give them separate handles. There’s also no technical reason to use two functions like this. Also, you should be using the ‘wp_enqueue_scripts‘ action hook. You should also use the ‘get_template_directory_uri()‘, as shown in the tutorial.

      You can achieve the result you’re after with the following:

      function ronald_load_scripts() {
          if ( ! is_admin() ) {
              wp_register_script( 'zoomPercent', get_template_directory_uri() . '/js/zoom.js', array( 'jquery' ) );
              wp_register_script( 'infiniteCarousel', get_template_directory_uri() . '/js/cursoule.js', array( 'jquery' ) );
      
              wp_enqueue_script( 'zoomPercent' );
              wp_enqueue_script( 'infiniteCarousel' );
          }
      }
      add_action( 'wp_enqueue_scripts', 'ronald_load_scripts' );
      

      I hope that helps! Let us know how you go.

      • Ronald dave

        Hey Japh. You’re Awsome.It really worked =>
        You Rock !!
        I’m a newbie in web-developing ,learning from different tutorials ,so just got very limited knowledge of all this !
        You got any advice for me … ?
        Thanks Aloooot .

  • http://www.greenleaf-net-solutions.com/ Colin Crawford

    Hi
    Thanks for the tutorial, I’m using a theme at the moment that has all scripts and css loaded in the header.php file and with reading around knew this was wrong to do it this way.

    I can now use what I have learned from your tutorial to load the files the WordPress way.

    Thanks Colin

  • http://mozthefox.com James Marshall

    Thanks Japh

    Really good article. I love reading about best practices and managed to follow your guide through very easily.

    Maybe some more best practise guides in the future?

    Cheers,
    James

  • http://webenvelopment.com Ben Racicot

    This all seems to work except with AJAX posts to php handlers. I CANNOT get outside AJAX functionality to work with WordPress. It makes the query but returns an entire file worth of data appended to the DB info. Puling my hair out.

  • http://freakify.com/ Ahmad Awais

    Great article
    I would like to know can we ad script and style both with same functions?
    How to add something inside the content below the post title in our dynamic plugin?

    • http://www.facebook.com/bilalvirgo10 Bilal Shahid

      offcourse we can add scripts and styles with the same function as follows:

      
      function add_scripts_styles(){
           wp_register_script(
                //all the arguments go here
           );
           wp_register_style(
                //all the arguments go here
           );
      
           wp_enqueue_script(
      
                //all the arguments go here
      
           );
      
           wp_enqueue_style(
      
                //all the arguments go here
      
           );
           
      }
      add_action('wp_enqueue_scripts', 'add_scripts_styles');
      
  • Ben

    Great article, thanks!

    Hoping you can help me…

    I’ve written a WP short-code, which results in some dynamically generated HTML (with IDs and class names calculated at run-time based on short-code attributes passed in), and some dynamically generated JS (using jQuery) that references these IDs/Classes and also uses some other integer values from the short-code to do its work.

    Until now, the dynamically generated JS is in-lined into the HTML body just above the HTML on which it acts. It’s not elegant, I know… but works well for the purpose.

    But it struck me that I should do this “properly”, so here I am reading your article!

    I’ve moved the JS into a separate file, and updated it to accept the class/id names and integer values as parameters. All good so far (and the registering and enqueuing is working sweetly – the script reference is showing up in the footer as required, along with its jQuery dependency ahead of it).

    But of course now it occurs to me that I’m still going to need to somehow generate a dynamic call to this function, in order to get the “run-time” values from the short-code passed into it.

    Is there a “best practice” and elegant way to trigger enqueued scripts (and pass them values known only at pre-processor run-time)? I’m guessing it can’t really be done without resorting to in-lining more JS?

    I guess I could set up some dummy HTML elements from which the JS can read its parameters from… but that seems chunky…

    It’s almost 4am here… so apologies up-front if the answers are obvious and if this was a really stooopid question! ;-)

    Thanks again for explaining this so well – everything else I read was either confusing, conflicting, or outright wrong!

    Cheers,
    Ben.

  • Pingback: Understanding The Enqueue Script: WordPress Themes & Plugins | Wptuts+

  • Pingback: Understanding The Enqueue Script: WordPress Themes & Plugins | Wptuts+

  • Pingback: Using responsive frameworks with WordPress – Alex Web Design

  • http://freakify.com Ahmad Awais

    Hey, Nice tutorial Japh, one thing I would like to ask here.
    If one uses this way for adding scripts or styles, the site/blog will have multiple separate files included in header or footer.
    What about optimization?
    Isn’t it better to append little CSS edits/codes to the end of Style.css of WordPress. Whereas using a single custom Js file for all js codes of your site?

    #justcurious

    • http://wp.envato.com/ Japh Thomson
      Author

      Hey Ahmad, thanks glad you liked the tutorial :)

      You’re right that doing things this way will mean there are more script / style files to load. However, it is better to keep things modular and in their proper places, and then use something like W3 Total Cache to minify and concatenate your scripts and styles for optimisation.

      Optimisation in this way means things are optimised, but also development is better.

      In the same way you hopefully wouldn’t suggest writing your code in a minified way, like:

      jQuery(document).ready(function($){do.all.the.things();});
      

      It’s nicer to write it out clearly:

      jQuery(document).ready(function($) {
          do.all.the.things();
      });
      

      Even that very simple example I think shows it’s better to code and plan clearly, and leave optimisation to optimisation tools :)

      • http://freakify.com Ahmad Awais

        I had been using this stuff in the similar way you mentioned in this tutorial since I bought Lite Speed server. For some unknown reasons, I experienced that Lite Speed server that I had, didn’t allow any plugin to minify the Js and CSS files. E.g W3TCache, WP Super Cache such plugins don’t work at my host. So, for my blog (http://freakify.com) I had to everything manually, that manual optimization led me to learn a lot of stuff and now I have more control over my site’s speed.

        For sometime I thought that I am the only one having this issue, or it could be my server’s configuration that are messing up with plugins, but later Aamir Atta (http://propakistani.pk) told me he is having same issue with Lite Speed server.

        After that, I gave it a second thought and stopped using the wp_enque function to avoid errors from my clients in future. I know it is not the best practice I am following now, but can you get me a better solution to avoid Lite Speed Server issues?

        • http://wp.envato.com/ Japh Thomson
          Author

          Hey Ahmad, I would recommend contacting the W3 Total Cache and WP Super Cache plugin developers and discussing Lite Speed compatibility with them. I’m sure there must be a work around for you there.

          Also, let’s discuss things related to article writing via email ;)

  • Gunnar

    This article doesn’t seem to fit under the “Cheat Sheets” category imho. Just my $.02.

    • http://wp.envato.com/ Japh Thomson
      Author

      Good point, Gunnar, not sure what happened there… I’ve put it back in its proper category now.

  • Yiafee Khan

    Your Article got 3 qualities:
    1. Its simple and easily readable.
    2. It does not try to focus on too many things.
    And 3. its a live saver topic for a newby in wp.

  • Pingback: Quick Tip: How To Use Gestures To Navigate WordPress Posts | Wptuts+

  • Pingback: Quick Tip: How To Use Gestures To Navigate WordPress Posts | Wordpress Webdesigner

  • Pingback: My Stream | Quick Tip: How To Use Gestures To Navigate WordPress Posts | My Stream

  • Gmall

    Hi Japh great tut! I was wondering how can someone include a javascript that its not custom. jQuery Datepicker UI for instance.It doesent need to register because it is included in wordpress right??Can you please give me an example of enqueue Datepicker UI ? Should we init after enqueuing that?Thanx a lot.

    • http://wp.envato.com/ Japh Thomson
      Author

      Hi Gmall, you simply enqueue with the handle that WordPress registers the script with. You can view the “Default scripts included with WordPress” section of the wp_enqueue_script() Codex page for the list of handles available. In the case of the jQuery UI Datepicker, you would use this:

      wp_enqueue_script( 'jquery-ui-datepicker' );
      

      This is actually also demonstrated in our recent article titled, “Building a Simple Announcements Plugin for WordPress“.

  • OpenTuition

    Hi, I am a newbie and I wondered if someone can help me out

    as I still do not understand

    , is it normal behaviour that plugins load their scripts on every page (frontend) even though they are of no use on those pages? like slideshows are only embedded (using shortcode on 3 pages on the whole site) and yet the scripts are loaded on homepage (there is no slideshow there) etc..

    how to exclude (or rather make the plugin load the script only on those 3 pages where the shortcode is present? assuming, I won’t have any idea what those pages will be called by the user of the plugin?

  • Pingback: How to create a custom slider with pods! Pt1 | Web Design for Idiots

  • Pingback: Common WordPress Development Mistakes and How to Fix Them | Wordpress Webdesigner

  • Rob

    Hello,

    I’ve got a Nextgen gallery which is only on my home page.

    I tried using the method above to load the script for it conditionally so it only loaded on the home page but it doesn’t work.

    The plugin enqueues all of it’s scripts to be in the front end so my conditional code just added it to the end of the already enqueued scripts.

    I read what you wrote under the heading Don’t Be Greedy and the entire codex page link but this advice must apply to plugin developers.

    As I understand it, it doesn’t matter if I try to conditionally load scripts because the plugin will load them across the board any way if they are coded to do so.

    Maybe that’s why OpenTuition encountered the situation described in the comment below.

    If a plugin is already enqueued to load its scripts, and they seem to precede any conditional loading, is there any thing we can do about it?

    Thanks and hope you can clarify this for me please?

  • Pingback: Common WordPress Development Mistakes and How to Fix Them | Wptuts+

  • Pingback: Как использовать жесты при навигации в постах WordPress | Wordpresso

  • Pingback: Как использовать жесты при навигации в постах WordPress | iostream.org.ua

  • Pingback: Как добавить JavaScript и CSS в WordPress тему или плагин | Wordpresso

  • Pingback: BlankSlate - the Best Starter Wordpress Theme

  • brodster

    how do i add a JavaScript and css in the admin area of WP?

    • http://wp.tutsplus.com/ Japh
      Author

      Hi @disqus_Q8GggJCoJI:disqus, basically instead of using the action “wp_enqueue_scripts”, use “admin_enqueue_scripts”, and that should work.

  • Atreyee

    Nice explanation …….hope I can use CSS & JS to my plugin will let you know once I have successfully done

  • Atreyee

    I am building a plugin now i want to add CSS effect at the frontend ,I know that I have to pass the function name in the add_action() as second parameter and need to mention the link ref for stylesheet at the head porrtion but I am not sure where to add the shortcode for the frontend page whether it has to be declared separately say add_shortcode( ‘TRM_DETAILS’, ‘function name’ ) or to the stylesheet function block.

    • http://wp.tutsplus.com/ Japh
      Author

      Hi @atreyee:disqus, you sound a little confused… there are no shortcodes involved in including CSS and JavaScript in your plugin.

      Can you clarify what you’re trying to do?

  • Atreyee

    Thnx Japh……..I am new developer don’t know if I am able to express let me try again..

    I have create a separate folder call CSS in the plugin folder and use wp_register_style() to register and wp_enqueue_style() to load & add_action( ‘wp_enqueue_scripts’, fn() ) and in the head portion.Now I want to see the effect of CSS .I have use shortcode to display the plugin say mine is subscription which I have added at one page,what else I have to do to see the color changes.

    • http://wp.tutsplus.com/ Japh
      Author

      Hi @atreyee:disqus, ok I think I understand now.

      Firstly, you use wp_enqueue_style() instead of putting the <link /> in the head portion. It’s bad practice to put it in the head section, leave that to the wp_enqueue_style() function. You must, however, make sure you have <?php wp_head(); ?> in the head section. This is where the <link /> will then ultimately be output.

      I hope that helps clarify!

  • VVE

    Hi Japh,

    Thanks for this article. However, I have in mind the following from the very start of it:

    Why we should register styles and scripts instead of enqueue-ing them directly?

    Let’s say I’m developing a WP theme and I want to enqueue everything in my functions.php file. I have 2 files to include – jquery.js and functions.js. Should I register the functions.js file first, or should I directly after jquery?

    Thanks

    • http://wp.tutsplus.com/ Japh
      Author

      Hey @disqus_7Y8JJhuNnp:disqus,

      Ok, so registering is useful in scenarios where you have a number of JavaScript files to utilise throughout your plugin or theme in various conditions. You register all the scripts in one place, to keep things nice and neat, and then you enqueue them via their handle in the relevant locations where / when you need them.

      In the scenario you mention, where you’re only enqueuing a single JavaScript file, then there’s no need to register first. Just enqueue where needed.

      Also, note that I say your scenarios is enqueuing a single JavaScript file. You do not need to enqueue jQuery, you need only provide it as a dependency in the enqueuing of your JavaScript file that needs it.

      Does that help clarify for you?

      • VVE

        Definitely. Thanks :)

  • Alexandre Gouveia

    Great article (first search result in Google ;), thanks Japh!

    One detail that it may help “LESS people” out (I found it in http://stackoverflow.com/questions/8082236/wp-enqueue-style-and-rel-other-than-stylesheet):

    What if you want to alter the rel=’stylesheet’ field on your included css files? Basically you just need to add a filter with a preg_replace($pattern, $replacement, $subject, $limit, $null)
    I’ve attached the image showing how I’ve done.

    And I still have 2 questions:

    - First: wouldn’t it be nicer to invoke the action for enqueueing in the header? Like this:

    [...]
    <link rel="stylesheet" href="”>
    <link rel="pingback" href="”>

    - Second: should I wp_deregister_script( ‘my_included_script’ ); before registering it? Like you’ve done for the jQuery. I know that the chances that some plugin uses exactly the same vendor script I’m using are low, but still, isn’t that a possibility that may cause conflicts?

    Cheers!

  • http://www.facebook.com/Ibrahim.Saqr Ibrahim Sakr

    sadly it did’t work for me …
    when trying to include this tutorial in my (shortcode.php file) it did’t work
    i’m trying to fix it but nothing happen ….

    here is my code


    function shortcode ($atts, $content = null) {
    extract(shortcode_atts(array(
    // attrs
    ), $atts));

    function shortcode_styles() {
    wp_register_style('shortcode_style', SHORTCSS .'/shortcode_style.css',array(),'10','all');
    wp_enqueue_style( 'shortcode_style' );
    }
    add_action('wp_enqueue_scripts', 'shortcode_styles');

    return 'shortcode';
    }
    add_shortcode("shortcode", "shortcode ");

    this is it … any idea why it does’t work !!!!!!

    thanks again

    • http://wp.tutsplus.com/ Japh
      Author

      Try something like this:


      function shortcode ( $atts, $content = null ) {
      extract( shortcode_atts( array(
      // attrs
      ), $atts ) );
      return 'shortcode';
      }
      add_shortcode( "shortcode", "shortcode" );

      function shortcode_styles() {
      wp_register_style( 'shortcode_style', SHORTCSS . '/shortcode_style.css', array(), '10', 'all' );
      wp_enqueue_style( 'shortcode_style' );
      }
      add_action( 'wp_enqueue_scripts', 'shortcode_styles' );

      Though you wil need to add some kind of check to ensure the shortcode is actually active before enqueueing. Best of luck!

      • http://www.facebook.com/Ibrahim.Saqr Ibrahim Sakr

        yaah

        worked perfectly

        many thanks japh …

  • http://www.facebook.com/Ibrahim.Saqr Ibrahim Sakr

    in my last comment here I wrote that you can use some code to (check to ensure the shortcode is actually active)

    now the best way I found to do that (may be anybody use IT) is ..
    1- register your script normally outside the shortcode function …
    2- then enqueue it exactly after opening shortcode function ….

    here is the code

    // here we register our script normally but don't enqueue it yet.
    function theme_styles() {
    wp_register_style('short_style', SHORTCSS .'/box_style.css',array(),'10','all');
    }
    add_action('wp_enqueue_scripts', 'theme_styles');
    // ----------------------------------------------------------------------------------------

    // now we begin the shortcode function
    function short_code ($atts, $content = null) {
    // here we enqueue the script ------
    wp_enqueue_style( 'box_style' );

    // then write your stuff
    extract(shortcode_atts(array(
    // atts
    ), $atts));

    return ' content ';
    }
    add_shortcode("shortcode", "short_code");

    thanks all of you ….

  • luiram

    This is great and probably the best practice, but I would really like to see more information on how and why we should load scripts in the footer. That kind of information is hard to find and understand.

    • http://wp.tutsplus.com/ Japh
      Author

      Hi @luiram:disqus, you can find information on this all over the place, such as this StackOverflow posting: http://stackoverflow.com/questions/5329807/benefits-of-loading-js-at-the-bottom-as-opposed-to-the-top-of-the-document

      It’s not a WordPress-specific issue, but rather general web development :)

      • luiram

        Hi Japh, Thats a great reference and I agree its web development in general. Sorry I guess I should have worded my statement better my fault. When starting out with WordPress I found it hard to find a good reference on how to enqueue scripts let alone in the footer. I was met with a spectrum of answers that made it hard to understand witch way was correct and the reasoning behind it. I just thought that kind of information would be useful in this tutorial as an “but wait even better enqueue your scripts in the footer” you know. But like you said you can find that information all over the place thanks and keep them coming I always find something amazing on this site.

        • http://wp.tutsplus.com/ Japh
          Author

          Ah, I see what you mean. Thanks for the clarification.

          I felt that discussing why and when to load scripts in the footer was beyond the scope of this tutorial, as really it’s a case-by-case issue.

          I’ll keep it in mind for future though!

  • Pingback: Re-developing Arden.nl | Arden de Raaij

  • Pingback: How to load JavaScript & Stylsheets | Responsive Theme Documentation

  • Pingback: Enqueue your scripts and styles the Wordpress way | Arden de Raaij

  • sonal

    When we use child theme directory, we need to get that path. As per WP Codex, In the event a child theme is being used, the parent theme directory URI will be returned, useget_stylesheet_directory_uri() to get the child theme directory URI.

    • http://wp.tutsplus.com/ Japh
      Author

      Thanks, @disqus_OjXLgrlgPJ:disqus. Yes, I believe this has been covered in previous comments also.

  • Pingback: Load scripts and styles in Wordpress – the right way

  • Simon

    Hi Thanks for the article.

    I cannot seem to get mine to work though.

    I am using the slidesjs slider on my homepage and this is the code I was using to call it, this is currently in my footer.php before the tag.

    $(function () {
    $(“.rslides”).responsiveSlides({
    pager: true,
    nav: true
    });
    });

    Now I have the 2 .js files pasted on my web server in the js folder. I’m new to php and javascript and do not know what steps I should take to reference the 2 .js files and run the above script.

    Do I need to use wp_enqueue and wp_register?
    Should I create a functions.php file?
    How do I run the script once I declare the above?

    Any help is much appreciated as I’ve been stuck for hours :)

    Thanks in advance.

  • Arthur Vincent Simon

    Is there a way to selectively include js or css based on page inside the functions?

  • Peter

    Hi Japh

    Many thanks for the article but unable to get this to work – however I am new to this!

    I have followed your example – I am trying to get simplecart (http://wojodesign.com/simplecartjs-v3-released/) to work with a WordPress site I am developing.

    In the function.php file I have added:

    function simplecart_with_jquery()
    {
    // Register the script like this for a theme:
    wp_register_script( ‘simplecart-script’, get_template_directory_uri() . ‘/js/simplecart.js’, array( ‘jquery’ ) );
    // For either a plugin or a theme, you can then enqueue the script:
    wp_enqueue_script( ‘simplecart-script’ );
    }
    add_action( ‘wp_enqueue_scripts’, ‘simplecart_with_jquery’ );

    in WordPress I have created the following directory structure:
    wp-content/plugins/simplecart/js/ and have uploaded the file simplecart.js

    If I upload the functions.php file I get HTTP Server error 500

    Can you explain what I am doing wrong!?

    Many thanks.

    • http://wp.tutsplus.com/ Japh
      Author

      Hi Peter , I can certainly help there :)

      The problem is that you’re mixing up theme development and plugin development, so we just need to change it around to be consist. What I mean is, you’re loading the script in a theme-based way, but you’re putting your files in a plugin-based directory structure.

      A plugin approach is best. So all you need to do is move the code you’re putting into functions.php into a plugin instead.

      Like this: https://gist.github.com/Japh/5147438

      Put that file in your wp-content/plugins/simplecart/ directory.

      • Peter

        Japh – thank you very much for this. I now have simpleCart working as a plugin in WordPress. As there are many questions on their site about getting simpleCart to work with WordPress I will paste a link back to this tut if OK with you?

        A couple of very minor updates to the information you have provided :
        the simplecart-for-wordpress.php file you created actually goes into the wp-content/plugins directory and the closing php syntax (?>) is missing from your file.

        Hopefully this will help others. Once again thanks.

        • http://wp.tutsplus.com/ Japh
          Author

          Hi Peter, glad it’s working for you :)

          The file should be able to go inside the simplecart directory just fine, did that not work for you?

          Also, the closing ?> was omitted deliberately. It is not required, and often preferred to be left out.

          • Peter

            Hi Japh – when I moved your php file from simplecart into the plugins directory it showed up in the WordPress Dashboard Plugins – then it was a case of activating the plugin (as per normal plugins).

            I am using Google Chrome – after activating the plugin if I right click on any of the WordPress pages and select Inspect Element I can see the call to the jQuery library and the simplecart.js file in the head element of the page.

            I thought you may have forgotten the ?> so I checked a book I have on WordPress about creating plugins and it showed ?> in the template file – but if you say it is not required I’ll go with the master :-)

            Your support is much appreciated.

          • http://wp.tutsplus.com/ Japh
            Author

            Hi Peter, it should (and does for me) show up in the WordPress Dashboard Plugins screen from either location, but I’d be surprised if it loaded the javascript correctly from just the “plugins” directory.

            Glad to hear it’s working for you either way :)

  • Pingback: Adding CSS to WordPress Theme Via functions.php File | WP Zac

  • http://www.ryanridgway.com/ Ryan Ridgway

    Great article. A little over my head for a newbie like me, but even the variable examples helped dramatically. I’d love to start coding my own widgets and plugins in the near future. Cheers – Ridg

    • http://wp.tutsplus.com/ Japh
      Author

      Thanks, @RyanRidgway:disqus ! Glad to hear it helped. Feel free to let me know when you release your first plugin, I’d love to check it out :)

  • Evert

    What happens if you call wp_enqueue_script twice for the same script? Will the script be included twice or is one of them ignored?

    • http://wp.tutsplus.com/ Japh
      Author

      Hey @EvertVd:disqus , one of them will be ignored. When a script is enqueued, the collection of scripts is checked to see if it’s there already first.

  • Pingback: A Beginner's Guide to Enqueuing jQuery | Wptuts+

  • Pingback: A Beginner’s Guide to Enqueuing jQuery | Wordpress Webdesigner

  • http://www.facebook.com/mittul.chauhan Mittul Chauhan

    You are absolutely right ..

    Follow the WordPress Rules provided by them or made by them.

    It would only make us happy and tension free in a coding life.

  • http://www.skyhittech.com/ Aqib Shahzad

    Thanks for sharing useful article, keep it up

  • Krunal Sojitra

    Hi,
    i have put this code in function.php and when i run it url print in home page
    function load_my_scripts(){

    wp_register_script(‘script’, bloginfo(‘template_url’).’/js/Script.js’,array(“jquery”), false , ’1.0′ );

    wp_enqueue_script(‘script’);

    }

    add_action(‘init’, ‘load_my_scripts’);

    • http://wp.tutsplus.com/ Japh
      Author

      Hello Krunal, if you try using one of the code snippets in the tutorial above, that might help you. There are several differences from the snippet you’ve included, which are most likely what are causing your issue.

      • Krunal Sojitra

        hi,

        use this one copy and past in yu function.php ans see the megic……………………….

        function load_my_scripts() {
        wp_deregister_script(‘jquery’);
        wp_register_script(‘jquery’, ‘http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js’, false, ’1.7.2′);
        wp_enqueue_script(‘jquery’);
        wp_register_script(‘scripts’, get_template_directory_uri() .’/js/scripts.js’, array(‘jquery’), ’1.0′, true );
        wp_enqueue_script(‘scripts’);
        }

        add_action(‘init’, ‘load_my_scripts’);

        now working problem is am using bloginfo(‘template_url’)

        • http://wp.tutsplus.com/ Japh
          Author

          Hello, notice there is an error in your add_action line. You also should not deregister and re-register jQuery. jQuery is already built into WordPress, so this is unnecessary and may cause you problems.

  • Pingback: Custom Content types, Sliders, Featured Sliders within wordpress | Serverhash Networks

  • Pingback: A Beginner’s Guide to Enqueuing jQuery | Mocco

  • Pingback: A Beginner’s Guide to Enqueuing jQuery | moccosk

  • Pingback: How to Make a Links Page Template With Scrollable Menu | Wptuts+

  • Pingback: How to Make a Links Page Template With Scrollable Menu | WordPress Tutorials 101

  • Pingback: How to Make a Links Page Template With Scrollable Menu | Wordpress Webdesigner

  • Pingback: How to Unleash the Power of Content |   eSolution Inc  

  • Pingback: Quickstart: adding HTML controls and handling events in a Windows Store app |   eSolution Inc  

  • Pingback: CSS Architectures, Part 1: Principles of Code Cleanup and the New Best Practices |   eSolution Inc  

  • Pingback: Wooservices | Developing WordPress Themes Using Responsive Frameworks

  • DHAVAL MODI

    I insert same code like this way

    function rm_scripts_basic()

    {

    wp_register_script( ‘mj’, get_template_directory_uri() . ‘/js/mj.js’ );

    wp_enqueue_script( ‘mj’ );

    wp_register_script( ‘bootstrap’, get_template_directory_uri().’/js/bootstrap.js’ );

    wp_enqueue_script( ‘bootstrap’ );

    wp_register_script( ‘bootstrap’, get_template_directory_uri().’/js/bootstrap.js’ );

    wp_enqueue_script( ‘bootstrap’ );

    wp_register_script( ‘organictabs.jquery’, get_template_directory_uri().’/js/organictabs.jquery.js’ );

    wp_enqueue_script( ‘organictabs.jquery’ );

    wp_register_script( ‘modernizr.custom.29473′, get_template_directory_uri().’/js/modernizr.custom.29473.js’ );

    wp_enqueue_script( ‘modernizr.custom.29473′);

    wp_register_script( ‘jquery-1.7.2.min’, get_template_directory_uri().’/js/jquery-1.7.2.min.js’ );

    wp_enqueue_script( ‘jquery-1.7.2.min’ );

    wp_register_script( ‘bootstrap’, get_template_directory_uri().’/js/jquery-ui-1.8.20.custom.min.js’ );

    wp_enqueue_script( ‘jquery-ui-1.8.20.custom.min’ );

    }

    add_action( ‘wp_enqueue_scripts’, ‘rm_scripts_basic’ );

    ?>

    But it not works what i do ? Plz reply me fast… js files are display but it not works at user side …

  • DHAVAL MODI

    I insert same code like this way

    function rm_scripts_basic()

    {

    wp_register_script( ‘mj’, get_template_directory_uri() . ‘/js/mj.js’ );

    wp_enqueue_script( ‘mj’ );

    wp_register_script( ‘bootstrap’, get_template_directory_uri().’/js/bootstrap.js’ );

    wp_enqueue_script( ‘bootstrap’ );

    wp_register_script( ‘bootstrap’, get_template_directory_uri().’/js/bootstrap.js’ );

    wp_enqueue_script( ‘bootstrap’ );

    wp_register_script( ‘organictabs.jquery’, get_template_directory_uri().’/js/organictabs.jquery.js’ );

    wp_enqueue_script( ‘organictabs.jquery’ );

    wp_register_script( ‘modernizr.custom.29473′, get_template_directory_uri().’/js/modernizr.custom.29473.js’ );

    wp_enqueue_script( ‘modernizr.custom.29473′);

    wp_register_script( ‘jquery-1.7.2.min’, get_template_directory_uri().’/js/jquery-1.7.2.min.js’ );

    wp_enqueue_script( ‘jquery-1.7.2.min’ );

    wp_register_script( ‘bootstrap’, get_template_directory_uri().’/js/jquery-ui-1.8.20.custom.min.js’ );

    wp_enqueue_script( ‘jquery-ui-1.8.20.custom.min’ );

    }

    add_action( ‘wp_enqueue_scripts’, ‘rm_scripts_basic’ );

    ?>

    But it not works what i do ? Plz reply me fast… js files are display but it not works at user side …

  • Pingback: How to Make a Links Page Template With Scrollable Menu - Wordpress Knowledge base