2

Say I wanted to add a site-wide snippet of JavaScript to my website but was using a child theme so as to not tamper with the original theme. Would I have to add a new .js file to the child theme, or could the script go into functions.php? Or, even better, could it be added with a plugin?

2 Answers 2

4

You can do different things:

  1. Enqueue the new JS file via plugin
  2. Enqueue the new JS file via functions.php
  3. Add your JS code into functions.php through wp_header or wp_footer

For adding new JS files to a wordpress site you should enqueue these files with wp_enqueue_style() and/or wp_enqueue_script().

This is the proper and safest way.

I would go the route and create a simple, small plugin for that, because this is theme independent.

You could also use an hook to wp_header or wp_footer. Inside this hook you can write your JS code.

But the proper way is enqueueing these files which will work something like this:

function prfx_frontend_enqueue() {
    wp_enqueue_style( 'my-plugin-css', plugins_url('/assets/css/plugin.css', __FILE__) );
    wp_enqueue_script( 'my-plugin-js', plugins_url('/assets/js/jquery.my-script-min.js', __FILE__), array('jquery'));
}
add_action('wp_enqueue_scripts', 'prfx_frontend_enqueue');
0

Yes.

Add the javascript file to the folder and call wp_enqueue_script() with the proper filename. You can do this either in the child theme or a plugin, it really does not matter (from a technical perspective).

If you aren't adding more functionality, I would not create a custom plugin for this and just include it within the child theme's function.php.

2
  • If I go the route of creating a new .js file, does it need a particular name, or could I just name it something relevant to its purpose?
    – McOwen
    Commented Jun 28, 2017 at 13:47
  • You can use any name you like - something relevant to its purpose is usually preferred. Then with calling wp_enqueue_script you provide that given name
    – kero
    Commented Jun 28, 2017 at 14:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.