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
You can do different things:
- Enqueue the new JS file via
plugin - Enqueue the new JS file via
functions.php - Add your JS code into
functions.phpthroughwp_headerorwp_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');
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.
-
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– McOwen2017-06-28 13:47:29 +00:00Commented 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_scriptyou provide that given namekero– kero2017-06-28 14:03:41 +00:00Commented Jun 28, 2017 at 14:03