Webdeveloper_Jelle
Webdeveloper_Jelle

Reputation: 2856

How can I include my own javascript file in wordpress?

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

Answers (1)

Sankalp Singha
Sankalp Singha

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)

  • $handle – what you'll use to refer to this particular script wherever you might need to enqueue it, and you have to include this variable at the very least
  • $src – the path to the source file within your plugin or theme
  • $deps – an array containing the $handle for any other scripts your script needs to run (i.e. a dependency)
  • $ver – the version number for your script, which can be used for cache-busting. By default, WordPress will use its own version number as the version number for your script
  • $in_footer – do you want your script to load in the footer? Set this to true or false. It is false by default, so it loads in the header where wp_head() is, and if you specify true it will load where wp_footer() appears in the theme

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

Related Questions