WordPress and JavaScript
WordPress can include JavaScript. This is done with WordPress themes.
Contents
wp_enqueue_script()
WordPress has a function named wp_enqueue_script()
which allows you to "enqueue" a script.
That is, the script is placed in a queue of activities which WordPress will perform as it generates the website.
From the WordPress Codex:
The safe and recommended method of adding JavaScript to a WordPress generated page, and WordPress Theme or Plugin, is by using wp_enqueue_script()
.
This function includes the script if it hasn't already been included, and safely handles dependencies.
You can use wp_enqueue_script()
in two places:
- In
functions.php
- In a WordPress plugin
functions.php
The optional functions.php
contains custom PHP for a WordPress theme.
To use JavaScript repeatedly within your site, you can either set the call for the JavaScript, or the script itself, in the head of your header.php template file, between the meta tags and the style sheet link, no differently than you would if you were using JavaScript in any HTML page.
To "load" the JavaScript file into your site, in the head, add something like this:
<script type="text/javascript" src="/scripts/emailpage.js"></script>
If your custom JavaScript isn't working after including the previous line of code in your header.php template file (TO DO: investigate "isn't working" -- what's going on?), use the following line of code:
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/pathto/yourscript.js"></script>
Include the leading forward slash "/", even if your file is located in the root of your theme.
Be sure that you define the type correctly, as your site will not validate without it.
Using JavaScript in a WordPress theme
In the spot where you wish to use the JavaScript, set the call for the JavaScript.
For example, you are using a JavaScript that sets a link for users to "email this page" to a friend, and you want it to be under the post title. It might look like this:
<a href="<?php the_permalink() ?>" rel="bookmark"> <?php the_title(); ?></a>
<script type="text/javascript"><![CDATA><! ]></script>
</pre>
Source: https://codex.wordpress.org/Using_Javascript