Reputation: 2856
I like to have my own Javascript included into my wordpress website.
When I put the link to the Javascript file inside my Header.php, I got no changes.
Anyone knows how to let my javascript work?
I tried to use the Header and footer Plugin to edit the Header and include my script, but it still doesn't work.
Upvotes: 1
Views: 815
Reputation: 4546
This is done using a WordPress function called wp_register_script, and here is its usage according to the WordPress Codex:
wp_register_script( $handle, $src, $deps, $ver, $in_footer );
You can put this in the functions.php
file.
So what are these variables and do we need them every time? (This is covered on the Codex page, so I'll be brief and use plain English)
Here is the most basic example for loading a custom script:
function wptuts_scripts_basic()
{
// Register the script like this for a plugin:
wp_register_script( 'custom-script', plugins_url( '/js/custom-script.js', __FILE__ ) );
// or
// Register the script like this for a theme:
wp_register_script( 'custom-script', get_template_directory_uri() . '/js/custom-script.js' );
// For either a plugin or a theme, you can then enqueue the script:
wp_enqueue_script( 'custom-script' );
}
add_action( 'wp_enqueue_scripts', 'wptuts_scripts_basic' );
First, we register the script, so WordPress knows what we're talking about. The way to find the path for our JavaScript file is different whether we're coding a plugin or a theme, so I've included examples of both above. Then we queue it up to be added into the HTML for the page when it's generated, by default in the where the wp_head() is in the theme.
The output we get from that basic example is:
<script type="text/javascript" src="http://yourdomain.com/wp-content/plugins/yourplugin/js/custom-script.js?ver=3.3.1"></script>
Upvotes: 2