Make WordPress Core


Ignore:
Timestamp:
02/23/2016 04:43:41 PM (9 years ago)
Author:
swissspidy
Message:

Script Loader: Introduce wp_add_inline_script().

This new function can be used to add inline JavaScript before and after enqueued scripts, just like wp_add_inline_style() works for CSS.

Props atimmer, abiralneupane, ocean90, swissspidy.
Fixes #14853.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/functions.wp-scripts.php

    r36074 r36633  
    8484
    8585    return wp_scripts()->do_items( $handles );
     86}
     87
     88/**
     89 * Add extra code to a registered script.
     90 *
     91 * Code will only be added if the script in already in the queue.
     92 * Accepts a string $data containing the Code. If two or more code blocks
     93 * are added to the same script $handle, they will be printed in the order
     94 * they were added, i.e. the latter added code can redeclare the previous.
     95 *
     96 * @since 4.5.0
     97 *
     98 * @see WP_Scripts::add_inline_script()
     99 *
     100 * @param string $handle   Name of the script to add the inline script to. Must be lowercase.
     101 * @param string $data     String containing the javascript to be added.
     102 * @param string $position Optional. Whether to add the inline script before the handle
     103 *                         or after. Default 'after'.
     104 * @return bool True on success, false on failure.
     105 */
     106function wp_add_inline_script( $handle, $data, $position = 'after' ) {
     107    _wp_scripts_maybe_doing_it_wrong( __FUNCTION__ );
     108
     109    if ( false !== stripos( $data, '</script>' ) ) {
     110        _doing_it_wrong( __FUNCTION__, __( 'Do not pass script tags to wp_add_inline_script().' ), '4.5.0' );
     111        $data = trim( preg_replace( '#<script[^>]*>(.*)</script>#is', '$1', $data ) );
     112    }
     113
     114    return wp_scripts()->add_inline_script( $handle, $data, $position );
    86115}
    87116
Note: See TracChangeset for help on using the changeset viewer.