While working on one of the WP projects, I needed to add some JS code. Normally, for such tasks, I use separate script files. However, in this case, the code was minimal, so I decided to place it directly into the HTML "body" of the document.
To do this, use the following PHP code:
add_action('wp_enqueue_scripts', function(){
if(!wp_script_is( 'jquery', 'done' ))
{
wp_enqueue_script( 'jquery' );
}
wp_add_inline_script( 'jquery-migrate', 'alert("Hello")' );
});Here's what we are doing:
The hook wp_enqueue_scripts — is responsible for enqueuing scripts for the frontend of the site
wp_script_is — checks whether a script has already been registered
wp_enqueue_script — enqueues the script by its ID (specified as a parameter)
wp_add_inline_script — creates our inline JavaScript code. The first parameter specifies the dependency script.
