1

forgive me but I am an amateur so I have limited knowledge.

I want to know the best way to add jQuery to my custom WordPress theme. Previously I just used the following code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>

I have learnt that apparently this is not the best practice way and that the best practice way is to use the wp_enqueue_script function to add jQuery. Therefore I created an index.php and functions.js file which I have copied down below.

html

<!DOCTYPE html>
<html>
    <head>
    <script>
        jQuery(document).ready(function(){
            jQuery('.enqTest').css('color','blue');
        });
    </script>
    </head>
    <body>
        <p class="enqTest">This font should be blue</p>
    </body>
</html>

functions.js

<?php
function adding_jquery{
    wp_enqueue_script('jquery');
}
add_action('wp_enqueue_scripts','adding_jquery');

My aim here is to use jQuery to change the font color of the text however I am trying to use wp_enqueue_script to load jQuery. It does not work. What am I missing here?

I have looked at other questions, interestingly another user said jQuery can only be loaded when it has been marked as a dependancy for a different script. Is this true? Would I then need to take the jQuery function out of my index.php file, add it to a new script file and register then enqueue that script file in the adding_jquery function in my functions.php file?

2
  • 1
    Did you put the second code in functions.js, or .php file? (There is functions.js above the code - is it a typo?) Apr 9, 2018 at 5:11
  • I can't believe that was it. Thanks, if you submit an answer I will mark it as "accepted".
    – Ruke
    Apr 9, 2018 at 5:31

1 Answer 1

1

wp_enqueue_scripts is a PHP hook, so you should use it in PHP. It won't work, if you add it to some JS file.

So if it's not a typo and you really put this code to functions.js file, then that's the reason it doesn't work.

0

Your Answer

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

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