wordpresswordpress-theming

How to wp_add_inline_script when there's no registered script to hook onto?


The docs for wp_add_inline_script state that it:

Adds extra code to a registered script.

How do you do it when there is no registered script? In my case, my only registered JS is before the closing body tag, and I want an inline script (js detection) in the head. Specifically I want my inline JS to come before my styles, but after the <title> and <meta> tags.

I tried to enqueue an empty script and then use it to hook my inline script onto, but that didn't work. Like this:

wp_enqueue_script( 'theme-js-detection', null, array(), null, false);

wp_add_inline_script( 'theme-js-detection', 
    '(function(H){H.className=H.className.replace(/\bno-js\b/,"js")})(document.documentElement)' 
);

Can this be done?


Solution

  • To place your script before the styles I would use the action hook wp_enqueue_scripts with high priority:

    function my_special_inline_script() {
        ?>
        <script>
            // your JS code
        </script>
        <?php
    }
    
    add_action( 'wp_enqueue_scripts', 'my_special_inline_script', 1, 1 );
    

    <title> and <meta> should be before this as long wp_head() is placed directly before the closing <head> tag as recommended.