wp_enqueue_script in the footer
Asked Answered
L

4

20

Having problems enqueuing a script in the footer.

wp_deregister_script('jquery');
wp_enqueue_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js', array(), false, true);

Here's the wp_enqueue_script definition:

wp_enqueue_script( 
     $handle
    ,$src
    ,$deps
    ,$ver
    ,$in_footer 
);

As you can see I am setting $in_footer to true. This does not work for me. Without that argument it works fine and puts it in header.php. Why doesn't it work with $in_footer?

Liv answered 19/3, 2012 at 17:42 Comment(0)
A
25

By default WordPress default JavaScripts won’t move to the footer, a workaround is to add its path :

wp_enqueue_script('jquery','/wp-includes/js/jquery/jquery.js','','',true);

See detailled post about this

Albumen answered 5/2, 2013 at 17:35 Comment(1)
using both: true, $in_footer = true works for me but I'm not sure why. When I remove the first true, it doesn't work, but using both together does.Boff
W
10

Make sure you have the wp_footer() right before the </body> tag. See the $in_footer parameter for more info. You also need to call this before wp_head has run. Try also using this action.

add_action('wp_enqueue_scripts', 'add_scripts_to_pages');

Another thing to try is using NULL as 3rd and 4th parameters.

Wojcik answered 19/3, 2012 at 18:21 Comment(1)
Make sure you have the wp_footer() right before the </body> tag. Just started WordPress this 2023 and this answer from 2012 fixed my problem. Thank you Nick!Wyoming
S
2

To follow on from Nick's reply just wanted to add an example. Add all 5 parameters for the wp_enqueue_script function then the script is loaded in the footer. Adding NULL instead of leaving the parameters blank works here for $deps and $ver.

Reference Format:

wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer );

General Example:

wp_enqueue_script('custom-handle-name', get_template_directory_uri() . '/custom-src.js', NULL, NULL, true );

Your Example:

wp_enqueue_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js', NULL, NULL, true);

Source: https://developer.wordpress.org/reference/functions/wp_enqueue_script/

Sassan answered 22/7, 2022 at 15:3 Comment(0)
D
1

As an addition to @Nick's answer;

if you have a PHP problem before wp_footer() you wont be able to see your script in footer. Source is https://wordpress.org/support/topic/enqueuing-scripts-in-footer-does-not-working-with-wordpress-36.

Dabster answered 21/2, 2015 at 11:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.