How to add custom JavaScript

You are here:
Estimated reading time: 1 min

This article refers how to add custom JS through the child theme. So before starting, make sure it’s installed and active. If it’s not installed, access Rey Theme > Dashboard in the backend and you should see a red button “Install Child theme” .

Now, if you want to avoid using a child theme, you can use a plugin such as Code Snippets .

So once you have the child theme installed, open functions.php and paste one of the codes below.

WordPress has a built-in code editor, so you can access WordPress > Appearance > Theme Editor , select Rey Child and after the page refresh, click on Theme Functions (functions.php) eg: https://d.pr/i/ULUmm6 .


Add JS code in Head

add_action('wp_head', function(){
	?>
	<script>
		// JS code here (make sure not to include script tags)
	</script>
	<?php
}, 100);

add_action('wp_footer', function(){
	?>
	<script>
		// JS code here (make sure not to include script tags)
	</script>
	<?php
}, 100);

Add JS code after body tag opens

add_action('wp_body_open', function(){
	?>
	<script>
		// JS code here (make sure not to include script tags)
	</script>
	<?php
}, 100);

As you can see in all examples, i already added the script tags, so make sure not to double load them. It’s important because it’ll crash the page.

Another thing to remember is that you can modify that “100” number, which stands for the hook’s priority. So making it smaller will force the hook to print the code earlier.

Was this article helpful?
Dislike 0
Views: 47

Join the conversation