wp_add_inline_script()

wp_add_inline_script with wordpress jquery

WordPress 4.5 comes with another useful function call wp_add_inline_script() which adds extra code to a registered script. This function is not much similar to wp_add_inline_style(). But functionality is same, adds inline Javascript.

Example

This will output:
i.e., this function accepts three parameters, handle, data and position. handle is a required parameter and it is the name of the script to add the inline script to. data is string containing the javascript to be added. Not that it doesn’t include <script>  tag. Another parameter is position this is optional and it accepts two values ‘before’ and ‘after’. Default value is ‘after’.

Add inline script after default jquery of WP

wp_add_inline_script() adds inline script before or after of a registered script. It doesn’t add independent inline scripts. For some cases we need to add inline scripts that depends to jquery library. As we know wordpress included it’s own jquery library in includes folder. And it doesn’t uses hosted jquery files. For enqueuing jquery dependent files we used jquery handle. So for adding inline script we use this code

 

But it doesn’t work. this is because jquery is a handle for adding a script bundle like jquery, jquery-migrate etc.

For adding inline scripts that depends jquery use this code

 

you can use jquery-core or jquery-migrate as handles

Add jquery library in footer in WordPress

By default jquery is included in header. this will reduce our site performance slightly. We change the position of jquery library to footer by adding this code

Happy coding and we always welcome discussions..

Leave a Reply

3 Comments

  1. RavanH

    Excellent tutorial 🙂

    Only the “move jquery to footer” snippet does not seem to work (anymore?) in WordPress 4.8 … any other method recommended ?

    • RavanH

      OK, found that when using all these together, the move to footer works:

      $scripts->add_data( ‘jquery’, ‘group’, 1 );
      $scripts->add_data( ‘jquery-core’, ‘group’, 1 );
      $scripts->add_data( ‘jquery-migrate’, ‘group’, 1 );

Next ArticleUnregister a post type using unregister_post_type