Dacramash Dacramash - 3 months ago 12
PHP Question

WordPress Move only Javascript to footer

Right now I am using a very simple function to move the javascript of WordPress to the footer:

function move_javascripts() {
remove_action( 'wp_head', 'wp_enqueue_scripts', 1 );
add_action( 'wp_footer', 'wp_enqueue_scripts', 5 );
}


The problem though is that this code seems to bring all the "scripts" to the footer, even the CSS... I've tried to find a way to move only the .js part but I can't find any...

So is there some way to only target the javascripts and move them to the footer without the CSS?

Answer

You are pretty much overkilling the whole WordPress Script system with this and to be honest - this is completely, I mean totally wrong. When you enque a script into WordPress you do this by wp_enqueue_script.

This function takes 5 parameters, of which the last one can be set to true, in order to load it in the footer.

Here is an excerpt of my functions.php:

if (!function_exists('wp_template_setup')) {

    wp_enqueue_script('modernizr-script', get_template_directory_uri() .   '/js/libs/modernizr.custom.js', '', '', true);
}
add_action('wp_enqueue_scripts', 'wp_template_setup');

The last paramter is set to true, which means that it will be loaded in the footer.

See the WordPress Codex for details: https://developer.wordpress.org/reference/functions/wp_enqueue_script/