How to add JS in footer

By Using wp_enqueue_script()

You can add your scripts to a JS file and then enqueue it properly. I assume you have added your scripts to file.js. Here’s how you enqueue it in the footer:

add_action('wp_enqueue_scripts','my_script_callback');
function my_script_callback(){
    wp_enqueue_script(
        'my-script',
        get_template_directory_uri().'/folder/file.js',
        array(jquery),
        null,
        true
    );
}

The last argument in wp_enqueue_script() determines whether your script should be enqueued in the footer or not.

The 3rd argument is optional, and is an array of dependencies.

By Using wp_footer()

You can also directly print your scripts in the footer, which is not always the best idea. However, this is how you do it:

function my_script() { ?>
    <script type="text/javascript">
        // Your code here
    </script><?php
}
add_action( 'wp_footer', 'my_script' );

Not that you have to wait for jQuery to be ready in such a method. You can enqueue jQuery if not already enqueue, by using this:

add_action( 'wp_head' , 'enqueue_jquery' )
function enqueue_jquery() {
    wp_enqueue_script( 'jquery' );
}

Leave a Comment