Question
What is the easiest way to add a script to head in WordPress?
You often need to add a custom <script>
inside <head>
.
For example it’s a simple way to add Google Analytics, tracking, syntax highlighting, custom JS libraries, etc.
I know that it is bad practice to edit directly the theme’s source code… So what is the easiest way?
I expected to have a text input in WordPress settings where I can add any custom code, but I can’t find it.
Answer
The best solution is to use a plugin to inject some code in WordPress.
Here’s the plugins that I recommend:
The first is straightforward and allows you to enter some JavaScript (or other code) directly in a text input in WordPress settings. Then your code is injected in the <head>
of every page of the WordPress website. It’s perfect for global scripts like Google Analytics (e.g. gtag.js).
The second plugin allows to add custom PHP and use WordPress hooks to add your JavaScript code. For example:
function add_my_script() {
echo '<script src="my.js"></script>';
}
add_action( 'wp_head', 'add_my_script' );