wp_add_inline_script

Adds extra code to a registered script.

Description

wp_add_inline_script( (string) $handle, (string) $data, (string) $position = 'after' ); 

Code will only be added if the script in already in the queue. Accepts a string $data containing the Code. If two or more code blocks are added to the same script $handle, they will be printed in the order they were added, i.e. the latter added code can redeclare the previous.

Parameters (3)

0. $handle (string)
Name of the script to add the inline script to.
1. $data (string)
String containing the javascript to be added.
2. $position — Optional. (string) => 'after'
Whether to add the inline script before the handle or after. Default after..

Usage

  1. if ( !function_exists( 'wp_add_inline_script' ) ) { 
  2. require_once ABSPATH . WPINC . '/functions.wp-scripts.php'; 
  3.  
  4. // Name of the script to add the inline script to. 
  5. $handle = ''; 
  6.  
  7. // String containing the javascript to be added. 
  8. $data = ''; 
  9.  
  10. // Optional. Whether to add the inline script before the handle 
  11. // or after. Default 'after'. 
  12. $position = 'after'; 
  13.  
  14. // NOTICE! Understand what this does before running. 
  15. $result = wp_add_inline_script($handle, $data, $position); 
  16.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/functions.wp-scripts.php  
  1. function wp_add_inline_script( $handle, $data, $position = 'after' ) { 
  2.  
  3. if ( false !== stripos( $data, '</script>' ) ) { 
  4. _doing_it_wrong( __FUNCTION__, sprintf( 
  5. /** translators: 1: <script>, 2: wp_add_inline_script() */ 
  6. __( 'Do not pass %1$s tags to %2$s.' ),  
  7. '<code><script></code>',  
  8. '<code>wp_add_inline_script()</code>' 
  9. ), '4.5.0' ); 
  10. $data = trim( preg_replace( '#<script[^>]*>(.*)</script>#is', '$1', $data ) ); 
  11.  
  12. returnwp_scripts)->add_inline_script( $handle, $data, $position );