Better Way to Add Inline Scripts

Better Way to Add Inline Scripts

All

WordPress / All 19 Views comments

In case you are a WordPress developer, you'll have used the WordPress hook wp_print_scripts so as to add any vital inline JavaScript. Alternately, you'll have used the perform wp_localize_script() so as to add your inline scripts. However do you know that not too way back, WordPress added a brand new perform for including inline JavaScript? Yep, as of WordPress model Four.5 and higher, we will use the superior perform wp_add_inline_script() to do the job.

One of many good issues about this newer perform is that you could affiliate it with any registered script AND embrace extra than simply JavaScript variables. This DigWP article explains how wp_add_inline_script() works, why it is higher than both of the alternate inline strategies, and the right way to help older (pre-Four.5) variations of WordPress. Alongside the best way, we'll take a look at some instance code you could customise and use in your personal WordPress tasks.

Inline scripts by way of wp_print_scripts

Up to now, a method so as to add inline scripts to the frontend was to make use of the motion hook wp_print_scripts (and/or admin_print_scripts for the Admin Space). Right here is an instance perform tailored from one among my plugins:

// inline script by way of wp_print_scripts
perform shapeSpace_print_scripts()  
        
        ?>
        
        <script>
                var var1 = <?php echo json_encode('var1'); ?>;
                var var2 = <?php echo json_encode('var2'); ?>;
                var var3 = <?php echo json_encode('var3'); ?>;
        </script>
        
        <?php
        

add_action('wp_print_scripts', 'shapeSpace_print_scripts');

This perform defines three variables based mostly on plugin choices, after which outputs them to the top part (on the front-end) utilizing the wp_print_scripts hook. To as an alternative add the script to the Admin Space, we might exchange wp_print_scripts with admin_print_scripts and name it a day.

Execs

Works each time so as to add any scripts to the <head> part of your net pages. No restriction on the code that's added; you possibly can add JS variables, conditionals, strategies, features, or no matter you need.

Cons

No solution to affiliate the added code with any registered script. You possibly can kind of management the relative location of the added code utilizing the $precedence parameter of the add_action() perform. However principally the output code is determined by different elements, so not any actual, constant strategy to management output location.

Inline scripts by way of wp_localize_script()

One other widespread method that builders embrace inline JavaScript is the perform, wp_localize_script(). This perform is supposed for localizing JavaScript variables to be used with internationalization and language translation. However I feel numerous builders use it simply so as to add inline scripts. Right here is an instance:

// inline scripts by way of wp_localize_script()
perform shapeSpace_enqueue_scripts() 
        
        wp_enqueue_script('shapeSpace_script', get_template_directory_uri() .'/js/script.js', array(), '1.zero', true);
        
        $array = array(
                'var1' => __('Worth for Variable 1', 'shapeSpace'),
                'var2' => __('Worth for Variable 2', 'shapeSpace'),
                'var3' => __('Worth for Variable Three', 'shapeSpace'),
        );
        
        wp_localize_script('shapeSpace_script', 'shapeSpace', $array);
        

add_action('wp_enqueue_scripts', 'shapeSpace_enqueue_scripts');

This instance perform enqueues our JavaScript file and provides it a deal with/ID of shapeSpace_script. Then an associative array that accommodates our variables is outlined. And lastly, the variables are handed to wp_localize_script() to be included inline together with the registered script, shapeSpace_script. This permits us to make use of any of the added JS variables like shapeSpace.var1, and so on.

Execs

This system is good as a result of it allows (learn: requires) affiliation with an present/registered script. So it offers a constant method to handle the relative location of your customized script output.

Cons

The one actual draw back to this in any other case strong method is which you can solely add JavaScript variables (i.e., var = 'worth';). So if you should add different kinds of inline scripts, like equations, conditionals, features or no matter, it is simply not attainable to do with wp_localize_script().

BEST: inline scripts by way of wp_add_inline_script()

Now that we have seen the professionals and cons of the 2 alternate inline-script methods, let us take a look at a greater method utilizing the brand new(er) WordPress perform, wp_add_inline_script(). In follow, it seems fairly just like wp_localize_script(), however can do a LOT extra. Right here is an instance:

// inline scripts by way of wp_add_inline_script()
perform shapeSpace_enqueue_scripts() 
        
        wp_enqueue_script('shapeSpace_script', get_template_directory_uri() .'/js/script.js', array(), '1.zero', true);
        
        $script  = 'var1 = '. json_encode('var1') .'; ';
        $script .= 'var2 = '. json_encode('var2') .'; ';
        $script .= 'var3 = '. json_encode('var3') .'; ';
        
        wp_add_inline_script('shapeSpace_script', $script, 'earlier than');
        

add_action('wp_enqueue_scripts', 'shapeSpace_enqueue_scripts');

This will not seem like a lot, however it's truly tremendous superior. We have now the perfect of BOTH worlds:

  • add ANY JavaScript snippet
  • affiliate with any registered script

Meaning we've full management over script content material and its relative location. Additionally word the third parameter, $place. That permits us to incorporate the $script both earlier than or after the $deal with, shapeSpace_script.

Professional Tip: All the time escape your inline JavaScript utilizing json_encode() or equal.

Execs

All execs. Add actually any JavaScript code inline, situated both earlier than or after the registered script, which itself could also be included within the head part or footer. So you've gotten full management.

Cons

None. All good.

Full Instance: Inline Script with Fallback

Placing the whole lot collectively, we will trend an entire method for including inline scripts that works in nearly ANY model of WordPress. For instance, I exploit the next Three-function method in my front-end posts plugin.

// enqueue scripts
perform shapeSpace_enqueue_scripts() 
        
        wp_enqueue_script('shapeSpace_script', get_template_directory_uri() .'/js/script.js', array(), '1.zero', true);
        
        shapeSpace_inline_script();
        

add_action('wp_enqueue_scripts', 'shapeSpace_enqueue_scripts');


// inline scripts WP >= Four.5
perform shapeSpace_inline_script() 
        
        $wp_version = get_bloginfo('model');
        
        if (version_compare($wp_version, 'Four.5', '>=')) 
                
                $script  = 'var1 = '. json_encode('var1') .'; ';
                $script .= 'var2 = '. json_encode('var2') .'; ';
                $script .= 'var3 = '. json_encode('var3') .'; ';
                
                wp_add_inline_script('shapeSpace_script', $script, 'earlier than');
                
        
        



// inline scripts WP < Four.5
perform shapeSpace_print_scripts()  
        
        $wp_version = get_bloginfo('model');
        
        if (version_compare($wp_version, 'Four.5', '<')) 
                
                ?>
                
                <script>
                        var var1 = <?php echo json_encode('var1'); ?>;
                        var var2 = <?php echo json_encode('var2'); ?>;
                        var var3 = <?php echo json_encode('var3'); ?>;
                </script>
                
                <?php
                
        
        

add_action('wp_print_scripts', 'shapeSpace_print_scripts');

That is the magic ticket proper there. Three easy features. First we enqueue our JavaScript file. From there, we name the second perform, which provides our inline script utilizing wp_add_inline_script() for WordPress variations Four.5 and higher. Then the third and ultimate perform is the fallback for older variations of WordPress. Something older than Four.5 will add our inline script by way of the wp_print_scripts hook. So backside line is that the above method works completely so as to add inline scripts to any model of WordPress going again to love 2.1 or one thing loopy.

Recap

Here's a recap simply FYI. Including inline scripts to WordPress:

  • wp_print_scripts / admin_print_scripts — Add any code to the header
  • wp_localize_script() — Add any JS variables to any registered script
  • wp_add_inline_script() — Add any JS code to any registered script

Additionally: Need to add inline CSS/fashion as an alternative of JavaScript? WordPress supplies a set of "add fashion" features which are just like these used for including scripts. For instance, take a look at wp_add_inline_style() and wp_print_styles.

Comments