How to Add Custom JavaScript Code to WordPress

How to Add Custom JavaScript Code to WordPress

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.

Posts on similar topics

Are you having problems with your WordPress site? Do you need additional functionality? A custom plugin or a new page?
Then write to me via the feedback form, and I will try to help you.

Write a comment

Your email address will not be published. Required fields are marked *