How to correctly add Javascript in functions.php

Your $scr in your wp_register_script() function is wrong. Given that your functions.php is inside your plugin, and your removeArrows.js is in the root of your plugin, your $scr should look like this

plugins_url( '/removeArrows.js' , __FILE__ )

Another point of note, it is always good practice to load your scripts and styles last. This will ensure that it will not get overriden by other scripts and styles. To do this, just add a very low priority (very high number) to your priority parameter ($priority) of add_action.

 add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts', 999 ); 

And always load/enqueue scripts and styles via the wp_enqueue_scripts action hook, as this is the proper hook to use. Do not load scripts and styles directly to wp_head or wp_footer

EDIT

For themes, as you’ve indicated that you now moved everything to your theme, your $scr would change to this

 get_template_directory_uri() . '/removeArrows.js'

for parent themes and this

get_stylesheet_directory_uri() . '/removeArrows.js'

for child themes. Your complete code should look like this

function wpb_adding_scripts() {
    wp_register_script('my_amazing_script', get_template_directory_uri() . '/removeArrows.js', array('jquery'),'1.1', true);
    wp_enqueue_script('my_amazing_script');
} 

add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts', 999 ); 

Leave a Comment