The wp_add_inline_script()
is designed for this purpose. It lets you add some inline JavaScript above or below an enqueued script. You just need to pass the contents of the script, without <script>
tags:
function custom_thing () {
if ( is_page( 2138 ) ) {
wp_enqueue_script( 'external-script', 'http://domain.com/external/script.js', array( 'jquery' ), 0, true );
wp_add_inline_script(
'external-script',
'jQuery( document ).ready( function( $ ) {
$( "div.specific" ).on( "click", "div.thing", function () {
//do somethiing
} );
} );',
'after'
);
);
}
add_action( 'wp_enqueue_scripts', 'custom_thing' );
The JavaScript itself is passed as a string, so just be careful about quotes. If the script is long enough that this becomes unwieldy, you’d be better off putting your JavaScript into its own file, and setting the external script as a dependency:
function custom_thing() {
if ( is_page( 2138 ) ) {
wp_enqueue_script( 'external-script', 'http://domain.com/external/script.js', array( 'jquery' ), 0, true );
wp_enqueue_script( 'custom-script', get_theme_file_uri( 'path/to/custom-script.js' ), array( 'jquery', 'external-script' ), 0, true );
}
}
add_action( 'wp_enqueue_scripts', 'custom_thing' );