Using wp_add_inline_script function. A Google Analytics example.

Until version version 4.4, in WordPress, there was only one way to add script files to the WordPress themes, the function wp_enqueue_script however, the new version 4.5 has introduced a new way, the function wp_add_inline_script that allows us to add javascript text scripts directly inside a template and that, in addition, it can be directly connected with other scripts. Let’s go to see how it works.

Example of using the wp_add_inline_script function

At bottom, this new function wp_add_inline_script is the equivalent for scripts files, to the wp_add_inline_script function is for CSS files. Let’s see how it works through and example based on adding the Google Analytics script to a WP theme.

the wp_add_inline_script function

The example that we’ll use to show how the WP function wp_add_inline_script works, is based on the code used to add Google Analitys to a website and it also shows:

  • how to connect any inline text scripts with a fixed script file,
  • how to introduce variables using this text scripts, and,
  • the selection of the kind of relation between the base script and the inline text script: after or before.

It’s really a powerful function (For a further information, see official documentation) so, let’s go to begin.

The code of Google Analitycs

The basic code proposed by Google for adding its Analytics module in any website is this next:

<script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

    ga('create', 'XX-YYYYYYY-Z', 'auto');
    ga('send', 'pageview');
</script>

The code is always the same for all websites and there is just a little part that’s different for each installation, specifically, the code line marked as XX-YYYYYYY-Z, that contains the code number for each website registered in Google Analytics.

    ga('create', 'XX-YYYYYYY-Z', 'auto');

Of course, if you have only got a single WordPress installation, please, forget you the rest of this article and simply, substitute you the XX-YYYYYYY-Z with your Analytics code, then write you an script file with the example, and just add you a wp_enqueue_script function inside your functions.php file. Best solutions have to be simple (for further informaction see the official documentation about Google Analytics function).

But, if you are developing a WP theme, or you have more than one single WordPress installation then, I’m sure that you would prefer to convert this XX-YYYYYYY-Z in a variable, and to be able to substitute it for dynamic values. Well, to do this, we could use the function wp_add_inline_script.

The Google Analytics example

Constructing the basic javascript file

The first step in our example is to modify the Google Analytics code and to change the line (the part that have to be different in each installation).

    ga('create', 'Fixed Code', 'auto');  >>>  ga('create', javascript var, 'auto');

converting the literal code in a javascript variable that can receive a value, for example:

<script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

    ga('create', theAnalyticsValue, 'auto');
    ga('send', 'pageview');
</script>

Then, we convert the Google Analitycs code in a javascript file, for example called putAnalytics.js, and we put this file in the theme directory (better in a subdirectory called /js).

Adding Google Analitycs javascript to our theme

Finally, we add this new javascript file to the functions.php file of our theme through function wp_enqueue_script but, in this case, we’ll use two lines, the first one for introducing the fixed script file of Analytics, and the second one for introducing the value of the variable theAnalyticsValue.

<?php
wp_enqueue_script( 'my-analytics-script', esc_url( get_template_directory_uri() ) . '/js/putAnalytics.js', array(), $wp_version, TRUE );
wp_add_inline_script( 'my-analytics-script', 'var theAnalyticsValue = "UA-MyRealCode-9";', 'before' );
?>

In the second line of the former example, we can see how this new function wp_add_inline_script works: with the first parameter we connect the inline script to the fixed script my-analytics-script, with the second parameter we introduce the inline javascript code with the adequated value for the variable theAnalyticsValue, and finally, with the last parameter we decide that we want to add this inline script before the fixed javascript file because, as we need the variable of the inline script code inside the fixed javascript file so, the variable must be introduced before the fixed javascript file.

These former PHP lines will produce a code output equivalent to in which the inline script part is shown before the javascript file.

<script>var theAnalyticsValue = "UA-MyRealCode-9";</script>
<script>(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', theAnalyticsValue, 'auto');
ga('send', 'pageview'); </script>

Extending the example

Actually, if we just make this little change, the result is quite useless because, at heart, we have to write this modification in each one of our WordPress instalations but, if for example we use the technique described in this former article for adding variables to WordPress Customizer, then we can convert the theAnalyticsValue into an real independent variable and then, our final PHP function could be something like.

<?php
// In a former function we have defined the var $apis['google']['analytics'].
// This var is set up via WordPress Customizer so in completely independent on the installation.
// See, http://www.joanmiquelviade.com/how-to-add-the-google-site-verification-code-or-other-api-parameters-to-your-wordpress-themes/

function adding_google_analytics_code () {
    $apis = get_theme_mod ( 'apis' );
    $codeV = $apis['google']['analytics']; // the WP Customizer var that contains the Google Analytics code for this web
    if ( ! empty( $code ) ) {
        wp_enqueue_script( 'myanalytics', esc_url( get_template_directory_uri() ) . '/js/putAnalytics.js', array(), $wp_version, TRUE );
        wp_add_inline_script( 'myanalytics', '/* < ![CDATA[ */ var theAnalyticsValue = "' . $codeV . '"; /* ]]> */', 'before' );
    }
} // and finally, we attach this function to the wp_enqueue_scripts action
add_action ( 'wp_enqueue_scripts', 'adding_google_analytics_code'); ?>

Now, we can simply introduce the Google Analytics code in a field in WordPress Customizer, and then this value will be automatically added to the theme via the PHP variable $codeV.

I hope that this function can be helpful for converting the scripts in a more flexible and powerful element of your themes.

Have a nice WordPressing!

Leave a Comment

   Mandatory field
You can use these HTML tags inside the commment.
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>