简体   繁体   中英

How can I run external js file from child theme in wordpress

I am using wordpress and I have some custom js in an external file in the root of my child theme. I want the reference to this js file written to the very end of the html document just before the closing body tag. I first tried hardcode the reference into footer.php. I verified that the reference to the external js file was correct in the html source but the javascript did nothing, and also did not throw any errors in firebug. The external file contained only:

jQuery(document).ready(function(){
    alert('hello')
});

So after googling this problem for a while I found that I will need to use

wp_register_script

and

wp_enqueue_script

I found documentation here and here but I am not very familiar with php...

Currently, I have added:

add_action('wp_enqueue_scripts', 'load_javascript_files');
function load_javascript_files() {
    wp_register_script('scripts', get_template_directory_uri() . 'wp-content/themes/maya_child/scripts.js', array('jquery'), true );
    wp_enqueue_script('scripts');
}

to my child theme's functions.php file. The result is that the reference to my custom scripts file does not print out in the source at all

Am I maybe missing a step, or have I screwed up the php? Do I need to add something to header.php? or footer.php?

It is probably the path to your javascript that's causing the problem. get_template_directory_uri() returns the path to your theme rather than the path to your site. Also, when you're using a child theme, this function still returns the uri of the parent theme - so it's not the best choice here.

Instead try get_stylesheet_directory_uri() :

add_action('wp_enqueue_scripts', 'load_javascript_files');
function load_javascript_files() {
    wp_register_script('scripts', get_stylesheet_directory_uri() . '/scripts.js', array('jquery'), null, true );
    wp_enqueue_script('scripts');
}

Note that neither of those functions returns a trailing slash on the uri, so you need to add that before the rest of your path eg. '/scripts.js'

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