Hi I was looking for a way to move wordpress default jQuery to the footer and I saw this answer: https://wordpress.stackexchange.com/a/225936/50584
So, I tried this approach in my child theme’s functions.php
file:
add_action( 'wp_enqueue_scripts', function() {
// Move jQuery to the footer
wp_scripts()->add_data( 'jquery', 'group', 1 );
wp_scripts()->add_data( 'jquery-core', 'group', 1 );
wp_scripts()->add_data( 'jquery-migrate', 'group', 1 );
});
But it is not pushing jquery to the footer. Any idea guys why is this happening? I want to avoid the de-register
& re-register
way of doing this.
Any help will be highly appreciated.
Important Update:
Since WP v3.9 there is no way of putting jquery scripts in your footer rather than using the de-register
& re-register
option. It is just simply cannot be done as the author pointed out below.
1 Answer
You should use the param $scripts
of the hook wp_default_scripts
. In this hook was en-queued all default scripts, also jQuery and you can change his data, like the group for load in footer.
add_action( 'wp_default_scripts', '_print_jquery_in_footer' );
function _print_jquery_in_footer( $scripts ) {
if ( ! is_admin() )
$scripts->add_data( 'jquery', 'group', 1 );
}
Also in the newer code style via anonymous function, like your question example; possible since php 5.3:
add_action(
'wp_default_scripts',
function( $scripts ) {
if ( ! is_admin() )
$scripts->add_data( 'jquery', 'group', 1 );
}
);
Edit: This will only work with WordPress versions lower than 3.9!