I have made a very simple JavaScript script. There is 1 .js file with a lot of code, and in the HTML file there is only 2 lines. The script works fine when I test it on a plain HTML page, but when I try it with WordPress, it doesn’t work.

I guess it has something to do with the path to the external .js file (src="https://wordpress.stackexchange.com/questions/177520/js/file.js").

What am I missing? Why isn’t my script loading correctly?

Edit: See comment to answer below, I have now added the code to the functions.php, but still not working.

Edit2: This is the code I use in the functions.php:

add_action( 'wp_enqueue_scripts', 'my_enqueue_front_scripts' );
function my_enqueue_front_scripts(){
    wp_enqueue_script( 'my-custom-scripts', get_stylesheet_directory_uri() . '/js/file.js' );
}

And this is the code in my head tag:

<script type="text/javascript"> url_detect.OnBack = function() { window.location.replace("URL.org"); } </script>

2 Answers
2

In WordPress you should enqueue your scripts (and styles) using the wp_enqueue_scripts action hook.

The main reason for this is to ensure that your script/style is only added once. You can, if you wish, aslo add conditions so that a script/style is only added to certain pages.

You say in your question that your script is located at js/file.js – presumabily this is within your Theme?

If so, try the code below (place it in functions.php), if not, please provide further details.

add_action('wp_enqueue_scripts', 'my_enqueue_front_scripts');
function my_enqueue_front_scripts(){

    wp_enqueue_script('my-custom-scripts', get_stylesheet_directory_uri().'/js/file.js');

}

Note that dispite the name, this action hook should also be used to enqueue your style sheets. For more information, please take some time to view the pages below –

  • wp_enqueue_scripts action hook

    • wp_enqueue_script function

    • wp_enqueue_style function

Leave a Reply

Your email address will not be published. Required fields are marked *