简体   繁体   中英

How to add script tag in head section to wordpress theme in cpanel?

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM