Reputation: 1201
I was trying to add a script tag to wordpress theme which seems to be an easy task but it is not working out!
I editing header.php file under wp-content>themes>them_name - header.php
When I add script tag and try to reload the page I cannot see the script tag in header section.
I even cleared browser cache that were suggested on internet.
Please suggest me some options as I am not a wordpress expert.
Thanks
Upvotes: 1
Views: 4489
Reputation: 357
General
The correct way to add scripts in WordPress is using wp_enqueue_script()
https://developer.wordpress.org/reference/functions/wp_enqueue_script/
Place the following code in functions.php:
function custom_wp_enqueue_scripts() {
wp_enqueue_script('script-name', get_template_directory_uri() . '/path/to/script/name.js', array(), '1.0.0', false);
}
add_action('wp_enqueue_scripts', 'custom_wp_enqueue_scripts');
Note the 5th argument is false
. This adds the script to the head rather than the end of the body.
Your specific case:
function custom_wp_enqueue_scripts() {
wp_enqueue_script('web-manager', 'domain.tld/js/web-manager.min.js', array(), '1.0.0', false);
}
add_action('wp_enqueue_scripts', 'custom_wp_enqueue_scripts');
Because your script requires the async
and data-key="abc123efg"
attributes you must also add this code to functions.php:
function custom_script_loader_tag($tag, $handle, $src) {
if ('web-manager' === $handle) {
$tag = '<script type="text/javascript" async src="' . $src . '" data-key="abc123efg"></script>';
}
return $tag;
}
add_filter('script_loader_tag', 'custom_script_loader_tag', 10, 3);
Upvotes: 2