wp_add_inline_script

Home » Functions » wp_add_inline_script

Function Name: wp_add_inline_script

Explanation: The wp_add_inline_script function is a powerful WordPress function that allows you to add inline JavaScript code to a specific script handle. This function is primarily used for adding custom JavaScript code that needs to be inserted and executed alongside an existing script.

When you enqueue a script using the wp_enqueue_script function, you may sometimes need to add additional custom JavaScript code that should be executed after the main script loads. Instead of modifying the original script file, which may not be ideal for various reasons, you can use wp_add_inline_script to add your custom code inline.

Usage: To use wp_add_inline_script, you need to provide two parameters: the script handle and the inline JavaScript code. The script handle is the unique identifier used when enqueuing the main script using wp_enqueue_script.

Here’s an example usage code:

// Enqueue the main script
wp_enqueue_script( 'my-script', 'path/to/my-script.js' );

// Add inline JavaScript code
$inline_code = "
    function myCustomFunction() {
        // Custom code here
    }
    myCustomFunction();
";
wp_add_inline_script( 'my-script', $inline_code );

In this example, we first enqueue the main script with the handle ‘my-script’ using wp_enqueue_script. Then, we define our custom JavaScript code in the $inline_code variable. Finally, we call wp_add_inline_script with the script handle and the inline code as parameters, which adds the code to be executed alongside ‘my-script’.

By using wp_add_inline_script, you can easily add custom JavaScript code without modifying the original script file, keeping your code organized and maintainable.

Please note that this function should be used cautiously, especially when dealing with third-party scripts, to ensure compatibility and avoid conflicts.

Learn More on WordPress.org

Register an account to save your snippets or go Pro to get more features.