Is there a way to append Javascript to the body in the script tag without using a file? Normally you would do it with

wp_enqueue_script('name', 'path/to/js/file');

Is there a way to include js in the script tag directly?

<script>My awesome code </script>

4 Answers 4


Yes, you can directly insert what you want in the header or the footer using the action wp_head or wp_footer

add_action('wp_head', 'custom_script');

function custom_script(){
      <script>My awesome code </script>


You only have to put this in functions.php of your child theme


You can also use the wp_add_inline_script() function in WordPress to add JavaScript code directly to the body of your web page without using an external file.

Here's an example of how you can use wp_add_inline_script() function to add JavaScript code to the body of your WordPress site:

add_action( 'wp_enqueue_scripts', 'my_custom_js' );
function my_custom_js() {
   wp_enqueue_script( 'my-js', 'path/to/js/file', array(), '1.0', true );
   wp_add_inline_script( 'my-js', 'console.log("My awesome code");' );

Check Hello Dolly plugin that comes with WordPress;

// File: wp-content/plugins/hello.php
// We need some CSS to position the paragraph
function dolly_css() {
    // This makes sure that the positioning is also good for right-to-left languages
    $x = is_rtl() ? 'left' : 'right';

    echo "
        <style type='text/css'>
            #dolly {
                float: $x;
                padding-$x: 15px;
                padding-top: 5px;       
                margin: 0;
                font-size: 11px;
add_action( 'admin_head', 'dolly_css' );

Like @benoti mentioned use wp_head hook in you don't need the admin side:

add_action('wp_head', 'function_callback' );

BTW, this plugins appends styles and the same works for scripts.


You can add this to your functions.php or snippet or plugin:

add_action('wp_head', function (){
<script>PASTE GLOBAL JS CODE HERE</script>
  • 1
    This hook only fires on the login page.
    – vancoder
    Commented Mar 23, 2023 at 21:42
  • Thanks! Solved with wp_head and anonymous function ;)
    – gtamborero
    Commented Mar 24, 2023 at 9:39

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.