2

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?
Like:

<script>My awesome code </script>
2

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>
      <?php

}

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

1

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;
            }
        </style>
    ";
}
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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