You can put a snippet of inline code just anywhere in a page or post, and also in the header.php file. Try something like this to see if the script appears in the page:
<script>
alert("Script is there!");
</script>
Often it is better to put scripts in external .js files. WordPress has a mechanism to enqueue them, which also works nicely together with caching etc.
function my_scripts() {
wp_enqueue_script('my-script', get_template_directory_uri() . '/js/my-script.js', array(), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );
hey bella, my script is:
<script type='text/javascript'>
var screenWidth = window.screen.width;
var element = document.getElementById('site-navigation');
if (screenWidth < 885) {
element.className = main-navigaion;
}
else
{
element.className = main-navigaion2;
}
</script>
so you recommend to save it in external file and then how is the function my_scripts needs to look like?
thank you.
Andrew Nevins
(@anevins)
WCLDN 2018 Contributor | Volunteer support
So where exactly did you save your external file?
public_html/wp/wp-content/themes/pictorico/js/menu2.js
thanks !
Andrew Nevins
(@anevins)
WCLDN 2018 Contributor | Volunteer support
- Create a Child Theme: http://codex.wordpress.org/Child_Themes#How_to_Create_a_Child_Theme
- In your Child Theme folder create a “js” folder
- Put your JS file inside that folder
- Create a functions.php file inside your Child Theme folder
- Inside your Child Theme functions.php file put this:
<?php
function my_scripts() {
wp_enqueue_script('my-script', get_stylesheet_directory_uri() . '/js/my-script.js', array(), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );
?>