The right hook
The wp_default_scripts
-hook only runs in the admin as it's called by wp_default_scripts()
on ~/wp-admin/load-scripts.php
where it's hooked at the end of the file.
So to move jQuery in public to the footer, you have to use a different hook: wp_enqueue_scripts
, which only runs in the public. No admin check needed.
<?php
defined( 'ABSPATH' ) or exit;
/* Plugin Name: jQuery to the footer! */
add_action( 'wp_enqueue_scripts', 'wcmScriptToFooter', PHP_INT_MAX -1 );
function wcmScriptToFooter()
{
$GLOBALS['wp_scripts']->add_data( 'jquery', 'group', 1 );
}
I'm using PHP_INT_MAX
, the maximum nr your system/server/OS is capable of. It makes very sure that your action triggers last to ensure that all other hooks have run previously. Still, nothing is 100% secure when it comes to priorities, but you got a very fair chance that it will work out.
Queueing the script
About your use of the $_SERVER
superglobal: You should stay back from using that. Command line interfaces (short: CLI - like Git/GNU Bash, Shell, etc.) won't be able to retrieve data from there. That means that all automated test environments like PHPUnit or SimpleTest will fail as well as all cronjobs or runwhen jobs won't be able to get any data from it.
The nice thing is, that schemeless, relative URls work out in all major browsers across all major versions. That means that //code.jquery.com/jquery-latest.min.js
will always give you the latest version.
function wpse124773_jQueryFromCDN()
{
wp_enqueue_script(
'jquery',
'//code.jquery.com/jquery-latest.min.js',
array(),
0,
true
);
}
The right version
If you stick with the "official" latest
version, WP might choke on it. The reason is simple: Core doesn't constantly use the latest version. Now we need to ensure that we're always using the version that WordPress currently uses. To achieve that, we're going to ask WP which version the current one is. That means that our script will always stay in line and up to date with core:
function wpse124773_jQueryFromCDN()
{
$version = $GLOBALS['wp_scripts']->registered['jquery']->ver;
wp_enqueue_script(
'jquery',
"//ajax.googleapis.com/ajax/libs/jquery/{$version}/jquery.min.js",
$GLOBALS['wp_scripts']->registered['jquery']->deps,
$version,
true
);
}