This question has been dealt with so many times over the years, and actually it is quite duplicated but anyway I'll try to summarize/update the "Best practice" approaches.
1. Do not replace the default WordPress jQuery unless you really have to. If you really care about performance you don't need jquery
2. Unless your theme or plugin does load jQuery, WordPress doesn't load it in the front-end area by default, usually we have to use wp_enqueue_script('jquery');
to load it. So first of all, make sure that you have jQuery enqueued. Use this code snippet to check your enqueued scripts:
// Show all enqueued scripts
add_action( 'wp_print_scripts', function () {
global $wp_scripts;
$enqueued_scripts = array();
foreach( $wp_scripts->queue as $handle ) {
$enqueued_scripts[] = $wp_scripts->registered[$handle]->src;
}
var_dump($enqueued_scripts);
} );
3. Do not using the wrong action hook init for adding your scripts, you should use wp_enqueue_scripts instead.
There are intentional safeguards in place to prevent critical admin scripts, such as jQuery core, from being unregistered. source
4. Most of solutions to replace the default jquery are outdated. Use this code instead (Tested on WP v5.1):
// Replace the default wp jquery with fallback
add_filter( 'wp_enqueue_scripts', 'replace_default_jquery_with_fallback');
function replace_default_jquery_with_fallback() {
// Change the version if needed
$ver = '1.12.4';
// Dequeue first then deregister
wp_dequeue_script( 'jquery' );
wp_deregister_script( 'jquery' );
// Load from Google
// Set last parameter to 'true' if you want to load it in footer
wp_register_script( 'jquery', "//ajax.googleapis.com/ajax/libs/jquery/$ver/jquery.min.js", '', $ver, false );
// Fallback
wp_add_inline_script( 'jquery', 'window.jQuery||document.write(\'<script src="'.includes_url( '/js/jquery/jquery.js' ).'"><\/script>\')' );
wp_enqueue_script ( 'jquery' );
}
Please note that:
- Using this way will also affect any plugin that depends on jQuery
- The correct way to completely remove a style or script is to dequeue it first then deregister it.
- init action hook is "Fires after WordPress has finished loading but before any headers are sent" use it with care.
- wp_enqueue_scripts is used to handle front-end scripts.
- admin_enqueue_scripts is used to handle admin scripts.
- login_enqueue_scripts used for login pages.
- Consider using jQuery Migrate if your code/plugins developed for jQuery versions older than 1.9.