0

I am fairly new to WordPress.

I am currently using a plugin which requires me to add a custom script before the </body> tag.

How do I do it?

2
  • Before what tag? Commented May 10, 2016 at 9:04
  • Thanks Gavin, I have edited the question. Before the </body> tag Commented May 10, 2016 at 9:05

1 Answer 1

4

You have two options for how to add the required JavaScript. The code below should be added to the functions.php file of your WordPress theme (or child theme).

This assumes the WordPress theme has used the wp_footer() function correctly.

function addScriptTagToBody() {
    ?>
    <script type="text/javascript">
        // JavaScript here..
    </script>
    <?php
}
add_action( 'wp_footer', 'addScriptTagToBody' );

Alternatively, if you want to link to an external JavaScript file, you can use the following:

wp_enqueue_script( 
    'custom-script', // A unique name for the script
    get_stylesheet_directory_uri() . '/custom-script.js', // Assumes the script is in your theme directory
    array( 'jquery' ), // An array of dependencies for your script
    '1', // Version number for your script
    true // Add script just before </body> tag
);

The fifth argument for wp_enqueue_script() lets you specify whether the <script src=""></script> is added in the <head></head> or just before the </body> tag.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, Kirk Beard. Where should I add my code in function.php?
It shouldn't matter really. Just add it at the end of your functions.php file. (functions.php, with an s).
Hi Kirk, I use the first method, this works perfectly, thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.