WordPress and JavaScript

From Wiki @ Karl Jones dot com
Revision as of 07:34, 10 December 2015 by Karl Jones (Talk | contribs) (wp_enqueue_script())

Jump to: navigation, search

WordPress can include JavaScript. This is done with WordPress themes.

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()</code.

This function includes the script if it hasn't already been included, and safely handles dependencies. </blockquote>

You can use <code>wp_enqueue_script() in two places:

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, 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.

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:

<h3 class="storytitle">
 <a href="<?php the_permalink() ?>" rel="bookmark">
 <?php the_title(); ?></a>
</h3>
<div class="emailpage">
 <script type="text/javascript"><!--//--><![CDATA[//><!--
 emailpage();
 //--><!]]></script>
</div>

See also

External links