2

I want to apply some javascript to my header and want to know what the best way to implement it is.

here is the source that contains the javascript I'm including - https://codepen.io/kaemak/pen/mHyKa/

Should I create a new javascript file then add it to the child theme, if so then I'm unsure of what to call the file and will it apply to the head from this location?

2

You should enqueue the script in child theme's functions.php. for example if name of the js file is custom.js and if you place it under js folder in your child theme, then in functions.php you should add

function my_custom_scripts() {
    wp_enqueue_script( 'custom-js', get_stylesheet_directory_uri() . '/js/custom.js', array( 'jquery' ),'',true );
}
add_action( 'wp_enqueue_scripts', 'my_custom_scripts' );

Here get_stylesheet_directory_uri() will return the directory of your child theme, then array( 'jquery' ) would make your js load after jquery, if your script requires js then you should use this else you can remove or you can add the dependent script here, then the last parameter true, is to make your js load at the footer.

  • if he want to enqueue js from the child he have to use get_stylesheet_directory_uri or the newest function get_theme_file_uri. – guido Jun 21 '18 at 17:07
  • get_theme_file_uri Searches in the stylesheet directory before the template directory so themes which inherit from a parent theme can just override one file, and he simply wants to add the new script from style-sheet directory, so get_stylesheet_directory_uri would be more suitable for this case. – Akshat Jun 21 '18 at 17:24
  • get_theme_file_uri doesn't override anything if used in a child theme, you simply try to get the uri in child and if not exists in parent. In case of an asset the override is performed by the handle. Btw get_template_directory_uri only search in the parent theme. That's why I commented. – guido Jun 21 '18 at 17:39
-1

Yes, create a new JavaScript file and just call it wherever you want, I would suggest to call it under footer that's the best way to call js files. You can add below code to your footer:

<script  src="<?php echo get_template_directory_uri(); ?>/filename.js"></script>

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.