WordPress add javascript in footer

I need to add a script in the site footer.
I’m just referencing the footer.php:

<script src="wp-content/file/script.js"></ script>

Read More

At Home functions normally, but when access a page child he does not find because search the directory:

site/page-child/wp-content/file/script.js.

I saw that I have to use:

  wp_enqueue_script ()

But where should I put this code?

Thank’s

Related posts

3 comments

  1. You just need to add a “/” before your url in order to start it from root like :

    <script src="/wp-content/file/script.js"></ script>
    

    Indeed at home page it looks for yoursite.com/wp-content but on other pages it searches yoursite.com/current-page/wp-content and obviously it results in 404.

    Adding / make it always look for yoursite.com/wp-content

  2. Adding <script src="wp-content/file/script.js"></ script> is not a clean way to load your JS files because this is not a relative URL and when you active your child theme probably your theme will not load your JS file, the solution is :

    <script src="<?php echo get_stylesheet_directory_uri(); ?>/js/script.js"></script>
    

    You need to add this to your footer.php file in your theme directory wp-contentthemesyour_themefooter.php

    but the best way is to use WP hooks to include your scripts, first you need to register them using

    wp_register_script( 'my_script_name', get_template_directory_uri(). '/js/script.js' );
    

    then simply load them

    wp_enqueue_script( 'my_script_name' );
    

    Don’t try to register and enqueue your scripts directly in your footer.php file, instead create a method in your functions.php template file then load your scripts using

    add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
    

    Note: To enqueue your scripts to the footer you need to set $in_footer parameter to true.

    Checkout wp_enqueue_script for more information.

  3. Since you seem to use WordPress, you can replace

        <script src="wp-content/file/script.js"></ script>
    

    with:

        <script src="<?php site_url('/wp-content/file/script.js'); ?>"></script>
    

Comments are closed.