1

I have looked all over the place and did not find a solution to my problem.

I have a child theme where I have a functions.php file where I try to register and enqueue the script the following way:

function wpb_adding_scripts() {
  wp_register_script('my_scripts', get_stylesheet_directory_uri('js/scripts.js', __FILE__), array('jquery'),'1.1', true);
  wp_enqueue_script('my_scripts');
}
add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );

And here is the script I am trying to load:

$(document).ready(function(){
  alert("test");
})

I made sure I have a "js" folder in my child directory where my scripts.js is.

But for some reason, this is not working for me.

Any one got an idea?

Thank you in advance for any help.

3

According to codex, get_stylesheet_directory_uri() does not including a trailing slash. So, you might want to use it in the following way:

function wpb_adding_scripts() {
  wp_register_script('my_scripts', get_stylesheet_directory_uri().'/js/scripts.js', array('jquery'),'1.1', true);
  wp_enqueue_script('my_scripts');
}
add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );

UPDATE

If you want to use jQuery in your scripts, you should do it in one of these ways:

  1. Use jQuery instead of $ to avoid conflict
  2. Create a self invoking function and pass $ to it.

Take a look at this example:

(function($){
    $(document).ready(function(){
      alert("test");
    })
})(jQuery);
  • Thank you for your help :). Unfortunately, it is not working for me :(. Is it because I am on localhost? I tried several browsers.. Another question: where I have 'my_scripts', from my understanding I can name that whatever I like, correct? – Serge Inácio Jul 11 '17 at 15:55
  • 1) Can you please elaborate 'not working'? What happens? Isn't your js file queued? does it have a wrong URL? or? 2) Yes you can name it anything you wish, as long as it doesn't conflict with any other scripts. – Jack Johansson Jul 11 '17 at 15:57
  • @SergeInácio Also there was a mistype in my code, sorry. I forgot to add a / to the end of the code. Try the updated answer. – Jack Johansson Jul 11 '17 at 15:59
  • Thanks again, but still no luck. what I mean by not working, is that the alert('test') is not firing. Other functions in the function.php file work – Serge Inácio Jul 11 '17 at 16:10
  • @SergeInácio That's strange. Any error log in console? Does it print the script in your theme's header? If so, is it the correct path? – Jack Johansson Jul 11 '17 at 16:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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