1

I want to add inline JavaScript to my WordPress frontend using wp_add_inline_script.

  • According to the docs it should work (as long as I add a script to the queue, which is true in my case)!

    Code will only be added if the script in already in the queue.

  • An equivalent snippet for styles instead of scripts works as expected (see my second snippet below)!

My current snippet which doesn't work:

add_action( 'wp_enqueue_scripts', function()
{
    wp_register_script( 'test-handle', '', array(), null );
    wp_enqueue_script( 'test-handle' ) );
    wp_add_inline_script( 'test-handle', 'does not work' )
} );

The following snippet works as aspected but is for styles instead:

add_action( 'wp_enqueue_scripts', function()
{
    wp_register_style( 'test-handle', '', array(), null );
    wp_enqueue_style( 'test-handle' ) );
    wp_add_inline_style( 'test-handle', 'works. is what I want.' )
} );

I'd like to use wp_add_inline_script because of its advantages (eg synchronize order, etc)...

1 Answer 1

1

While the function wp_add_inline_script was already implemented it didn't work in WordPress version 4.x. Since WordPress version 5.x its working just as expected.

add_action( 'wp_enqueue_scripts', function()
{
    wp_register_script( 'test-handle', '', array(), null );
    wp_enqueue_script( 'test-handle' ) );
    wp_add_inline_script( 'test-handle', 'does work since WP 5.x' )
} );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.