简体   繁体   中英

Integrating javascript files in wordpress custom theme

I know that there already are several topics with this matter but none of them seem to resolve my problem.

I want to link in a custom WordPress theme that I am creating several JavaScript files. I've tried a lot of possible ways and none of them seem to work for me.

To skip all the ways I've already tried to add the files please tell me for example how can I add the file "prettyPhoto.js" in order to work in my custom theme.

Thank you, Andi

The right way is to use wp_register_script and wp_enqueue_script . Using these will instruct WordPress to load your script after any dependent scripts.

So say your prettyPhoto.js file is in mytheme/js . In functions.php , add something like:

<?php
add_action('wp_enqueue_scripts', 'mytheme_load_scripts');
function mytheme_load_scripts() {
  // this only registers the script with WordPress
  wp_register_script('prettyPhoto', get_stylesheet_directory_uri().'/js/prettyPhoto.js');
  // this actually loads the script in `wp_head`
  wp_enqueue_script('prettyPhoto');
}
?>

If prettyPhoto.js is dependent on jQuery or something, then you specify this in wp_register_script . Doing the below will tell WordPress to ensure jQuery is loaded before your script is loaded.

<?php
wp_register_script('prettyPhoto', get_stylesheet_directory_uri().'/js/prettyPhoto.js', array('jquery'));
?>

See wp_register_script and wp_enqueue_script in the codex for more.

This article will probably help, too.

I guess it didn't work for You, because You probably forgot about placing wp_head()

immediately before tag in a theme template (ex. header.php, index.php)

or about placing wp_footer()

immediately before tag in a theme template (ex. footer.php, index.php).

Take some time and make yourself familiar with the Theme Development Checklist .

It's hard to guess without seeing the template and without knowing what You've tried already, but what You need is the wp_enqueue_script function (in functions.php ) together with wp_head() and|or wp_footer() (in the template).

  1. Make sure, there is wp_head() right before </head> in the template.
  2. Make sure, there is wp_footer() right before </body> in the template.
  3. Place the following code in functions.php :

     function my_theme_add_javascript() { wp_enqueue_script( 'pretty-photo', get_template_directory_uri() . '/js/prettyPhoto.js', array('jquery') ); } add_action('wp_enqueue_scripts', 'my_theme_add_javascript'); 

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