0

I want to move jquery.js from header to footer. I have tried following code:

//Remove jQuery Default
function replace_jquery() {
 if (!is_admin()) {
 wp_deregister_script('jquery');
 }
}
add_action('init', 'replace_jquery');

//Load on Footer
add_action('wp_footer', 'jquery_code');
function jquery_code(){
?>
<script type='text/javascript' src='https://example.com/wp-includes/js/jquery/jquery.js'></script>
<?php
};

The issue is that If I run first piece of above code, js files of my theme are removed with jquery.js. Because theme's static js files is calling via array( 'jquery' ) attributes.

I just want to move jquery only from header to footer.

NOTE: I have tried other suggestions on Stackexchange but none of them didn't work on my blog. (Such us: Enqueue core jQuery in the footer?)

How can I do it?

1 Answer 1

0

When you deregister jQuery, you have to register it again. Try this code

UPDATE: You have to deregister jQuery first (first part of your code), so the final code should be:

//Load on Footer
add_action('wp_enqueue_scripts', 'register_jquery');
function register_jquery() {
    wp_deregister_script('jquery'); // remove original jQuery
    wp_register_script( // add custom jQuery in footer
       'jquery', 
       'https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js',
       array(), // dependencies
       null, // version
       true); // load in footer?
    wp_enqueue_script('jquery');
}

But it's NOT RECOMMENDED to load custom jquery in wordpress.

4
  • Thank your for your help friend :) But still jquery is loaded on header. This situation is related to theme codes? Commented Jan 10, 2019 at 15:22
  • If I add below code instead of yours, it can create any issue? //Load on Footer add_action('wp_footer', 'jquery_code'); function jquery_code(){ ?> AUTO-DEREGISTERED THEME JS CODES HERE <script type='text/javascript' src='example.com/wp-includes/js/jquery/jquery.js'></script> <?php }; Commented Jan 10, 2019 at 15:48
  • Yes, because jQuery will be not registered and the other scripts (dependencies) will be not work. One thing about my answer - don't forget to deregister jquery first (first part of your code - Remove jQuery Default, and after that - my code.
    – troxxx
    Commented Jan 10, 2019 at 16:10
  • @SerdarKoçak if my answer helped you, please mark my answer ;)
    – troxxx
    Commented Jan 11, 2019 at 10:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.