SlideShare a Scribd company logo
Weaving JavaScript
-- in and out of --

WordPress
WordCamp Las Vegas 2013
slides: http://www.slideshare.net/jeffreyzinn/wclv13-javascript
code: https://gist.github.com/jeffreyzinn/7953881

Friday, December 13, 13
Jeffrey Zinn
• Co-founder of Pixel Jar
• WordCamp OC co-organizer
• AdSanity co-developer
• @jeffreyzinn
• jeff@jzinn.us
surfer, WordPress fanboy,
avid backpacker, euro gamer,
soccer hooligan, traveler,
voracious coffee drinker

Friday, December 13, 13
Need To Know
1. JavaScript
2. Functions
3. Actions

Friday, December 13, 13
Topics
1. Loading JavaScripts - making
JavaScripts available to themes, plugins
and code
2. Available Libraries - JavaScripts that
are already available in a default
WordPress installation
3. Using CDNs - load JavaScripts from nonlocal sources
4. Localize Script - making data from PHP
available in JavaScript
Friday, December 13, 13
1. Loading Javascript
making JavaScripts available to themes,
plugins and code

Friday, December 13, 13
Example 1
What we are doing:
Load a custom JavaScript called custom.js from
my theme’s /js directory.

load
me

Friday, December 13, 13
Do Not...
...simply add a <script> tag into a template or
header file
<head profile="http://gmpg.org/xfn/11">
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8" />
<title>WP Starter Setup — Just another WordPress site</title>
<link rel="stylesheet" href="http://wp.start/wp-content/
themes/billerickson-BE-Genesis-Child-c73d97a/style.css"
type="text/css" media="screen" />
<script type='text/javascript' src='http://wp.start/wpincludes/js/jquery/jquery.js?ver=1.7.2'></script>
<script type="text/javascript" src="http://wp.start/wpcontent/themes/billerickson-BE-Genesis-Child-c73d97a/js/
custom.js"></script>
</head>

Friday, December 13, 13
Do Not...
...echo out a <script> tag using using the
wp_head/wp_footer action

<?php
add_action( 'wp_head', 'load_my_script' );
function load_my_script() {
$src = get_stylesheet_directory_uri() . '/js/custom.js’;
echo '<script type="text/javascript" src="' . $src . '”></script>';
}
?> 

Friday, December 13, 13
Functions
• wp_register_script() - get ready to use a
script (but don’t load it up just yet)

• wp_deregister_script() - remove a
registered script

• wp_enqueue_script() - load that script
into my theme/plugin so I can use it

• wp_dequeue_script() - remove an
enqueued script

Friday, December 13, 13
The Process
1. Use the wp_enqueue_scripts action to
load in your selected JavaScripts
2. Stage a script by calling the
wp_register_script function
3. Load the script from #2 using the
wp_enqueue_script function
Often on functions.php, but could be
elsewhere in your theme or plugin code.
Friday, December 13, 13
wp_register_script()
Description:
Safe way of registering JavaScripts in
WordPress for later use:
<?php 
wp_register_script
( $handle, $src, $deps, $ver, $in_footer );
?>
string
string
array
string
boolean
give the file
a unique
nickname
(required)

Friday, December 13, 13

where is
the file

what other
files have to
be loaded
first

the
script’s
version
number

should WP
try and load
this in the
footer
wp_register_script()
Description:
Safe way of registering JavaScripts in
WordPress for later use:
<?php 
wp_register_script
( $handle, $src, $deps, $ver, $in_footer );
?>
string
string
array
string
boolean

Note:
admin_enqueue_scripts to call it on the admin side, or use
login_enqueue_scripts for login screens.

Friday, December 13, 13
Example 1.1
What we are doing:
Load a custom JavaScript called custom.js from
my theme’s /js directory.
<?php 
add_action( 'wp_enqueue_scripts', 'simple_load_script' );
function simple_load_script() {
$src = get_stylesheet_directory_uri() . '/js/custom.js' ;
wp_register_script( 'custom-script', $src, array( 'jquery' ), '1', TRUE );
}
?> 

wp_enqueue_script( 'custom-script' );

Friday, December 13, 13
Example 1.2
What we are doing:
Register and enqueue custom.js as separate
actions.
<?php 
/** Register JavaScripts **/
add_action( 'wp_enqueue_scripts', 'custom_register_scripts' );
function custom_register_scripts() {
$src = get_stylesheet_directory_uri() . '/js/custom.js' ;
wp_register_script( 'custom-script', $src, array( 'jquery' ), '1', TRUE );
}
/** Enqueue JavaScripts **/
add_action( 'wp_enqueue_scripts', 'custom_enqueue_scripts' );
function custom_enqueue_scripts() {
wp_enqueue_script( 'custom-script' );
}
?> 

Friday, December 13, 13
Example 1.3
What we are doing:
Load custom.js conditionally for pages only.
<?php 
add_action( 'wp_enqueue_scripts', 'custom_script_for_pages' );
function custom_script_for_pages() {
$src = get_stylesheet_directory_uri() . '/js/custom.js' ;
wp_register_script( 'custom-script', $src, array( 'jquery' ), '1', TRUE );

}
?> 

if( is_page() )
wp_enqueue_script( 'custom-script' );

Friday, December 13, 13
Example 1.4
What we are doing:
Load custom.js without registering.
<?php 
add_action( 'wp_enqueue_scripts', 'custom_script_enqueue' );
function custom_script_enqueue() {
$src = get_stylesheet_directory_uri() . '/js/custom.js' ;
wp_enqueue_script( 'custom-script', $src, array( 'jquery' ), '1', TRUE );
}
?> 

Friday, December 13, 13
(works with styles too)
• wp_register_style()
• wp_deregister_style()
• wp_enqueue_style()
• wp_dequeue_style()

Friday, December 13, 13
2. Available Libraries
JavaScripts that are already available in
a default WordPress installation

Friday, December 13, 13
Available Libraries
Script

Handle

SWFUpload

swfupload

jQuery UI Core

jquery-ui-core

jQuery UI Accordion

jquery-ui-accordion

jQuery UI Datepicker

jquery-ui-datepicker

ThickBox

thickbox

jQuery Hotkeys

jquery-hotkeys

...plus many other scripts
http://codex.wordpress.org/Function_Reference/
wp_enqueue_script#Default_scripts_included_with_WordPress
Friday, December 13, 13
Example 2.1
What we are doing:
Load and use jQuery UI Draggable, which is preregistered.
<?php 
add_action( 'wp_enqueue_scripts', 'enqueue_draggable' );
function enqueue_draggable() {
wp_enqueue_script( 'jquery-ui-draggable' );
}
?> 

Friday, December 13, 13
Example 2.2
What we are doing:
Load a custom script called draggable.js in /js
directory that uses jQuery UI Draggable and
make our widgets draggable!
<?php 
/** Corresponding JavaScript: https://gist.github.com/3718542

**/

add_action( 'wp_enqueue_scripts', 'custom_draggable_script' );
function custom_draggable_script() {
$src = get_stylesheet_directory_uri() . '/js/draggable.js' ;
wp_register_script( 'custom-draggable-script', $src,
array( 'jquery','jquery-ui-draggable' ), '1', TRUE );
wp_enqueue_script( 'custom-draggable-script' );
}
?> 
Friday, December 13, 13
3. Using CDNs
load JavaScripts from non-local sources

Friday, December 13, 13
Example 3.1
What we are doing:
Load jquery from an external source.
<?php 
add_action( 'wp_enqueue_scripts', 'load_jquery_from_googleapis' );
function load_jquery_from_googleapis() {
wp_deregister_script( 'jquery' );
$src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js';
wp_register_script( 'jquery', $src, array(), '1.10.2' );
wp_enqueue_script( 'jquery' );
}
?> 

Friday, December 13, 13
Example 3.1
What we are doing:
Load jQuery from an external source.
<?php 
add_action( 'wp_enqueue_scripts', 'load_jquery_from_googleapis' );
function load_jquery_from_googleapis() {
wp_deregister_script( 'jquery' );
$src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js';
wp_register_script( 'jquery', $src, array(), '1.10.2' );
wp_enqueue_script( 'jquery' );
}
?> 

Friday, December 13, 13

Keep same handle
for dependencies
Example 3.1
What we are doing:
Load jquery from an external source.
<?php 
add_action( 'wp_enqueue_scripts', 'load_jquery_from_googleapis' );
function load_jquery_from_googleapis() {
wp_deregister_script( 'jquery' );
$src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js';
wp_register_script( 'jquery', $src, array(), '1.10.2' );
wp_enqueue_script( 'jquery' );
}
?> 

Friday, December 13, 13

Be careful of version #,
is it still compatible with
WP and your stuff?
4. Localize Script
making data from PHP
available in JavaScript

Friday, December 13, 13
Do Not...
...use PHP to build JavaScript code
<?php
add_action( 'wp_head', 'build_my_script' );
function build_my_script() {
global $current_user;
get_currentuserinfo();
echo
echo

"rn";
'<script type="text/javascript">' . "rn";
echo "t" . 'var userid = "' . esc_js( $current_user->ID ) . '";';
echo "rn";
echo "t" . 'var fname = "' . esc_js( $current_user->user_firstname ) . '";';
echo "rn";
echo '</script>' . "rn";

}
?> 

Friday, December 13, 13
wp_localize_script()
Description:
Send PHP data into the JavaScript data world.
Usage:
<?php 
wp_localize_script( $handle, $object_name, $l10n ); 
?>
string
string
array
nickname
of script to
send data to
(required)

Friday, December 13, 13

what to call
the object
when it is
in the script
(required)

what data
to send to
the script
(required)
wp_localize_script()
Description:
Send PHP data into the JavaScript data world.
Usage:
<?php 
wp_localize_script( $handle, $object_name, $l10n ); 
?>

Note:
wp_localize_script() must be called AFTER the script it's being
attached to has been enqueued. It doesn't put the localized
script in a queue for later queued scripts.

Friday, December 13, 13
wp_localize_script()
Description:
Send PHP data into the JavaScript data world.
Usage:
<?php 
wp_localize_script( $handle, $object_name, $l10n ); 
?>

Also Note:
$l10n (array) (required) The data itself. The data can be either
a single or multi (as of 3.3) dimensional array.

Friday, December 13, 13
Example 4.1
What we are doing:
Send user ID and first name from PHP over to
custom.js and alert the user.
<?php
/** Corresponding JavaScript: https://gist.github.com/3718839

**/

add_action( 'wp_enqueue_scripts', 'send_user_data_to_custom' );
function send_user_data_to_custom() {
$src = get_stylesheet_directory_uri() . '/js/custom.js' ;
wp_register_script( 'custom-script', $src, array( 'jquery' ), '1', TRUE );
wp_enqueue_script( 'custom-script' );
global $current_user;
get_currentuserinfo();
$data = array( 
'userid' => $current_user->ID,
'fname'  => $current_user->user_firstname
);
}
?> 

wp_localize_script( 'custom-script', 'userinfo', $data );

Friday, December 13, 13
Example 4.1
What we are doing:
Send user ID and first name from PHP over to
custom.js and alert the user.
<?php
/** Corresponding JavaScript: https://gist.github.com/3718839

**/

add_action( 'wp_enqueue_scripts', 'send_user_data_to_custom' );
in JavaScript the data can be called by
function send_user_data_to_custom() {
userinfo.userid and userinfo.fname

using

$src = get_stylesheet_directory_uri() . '/js/custom.js' ;
wp_register_script( 'custom-script', $src, array( 'jquery' ), '1', TRUE );
wp_enqueue_script( 'custom-script' );

+

global $current_user;
get_currentuserinfo();
$data = array( 
'userid' => $current_user->ID,
'fname'  => $current_user->user_firstname
);
}
?> 

wp_localize_script( 'custom-script', 'userinfo', $data );

Friday, December 13, 13
Example 4.1
JavaScript: custom.js
jQuery(document).ready(function($){
alert("Hey, " + userinfo.fname + ", your user ID is " + userinfo.userid + ". Boom!");
});

Friday, December 13, 13

More Related Content

PDF
Hooks WCSD12
Jeffrey Zinn
 
PDF
Mocking Demystified
Marcello Duarte
 
PDF
Forget about Index.php and build you applications around HTTP - PHPers Cracow
Kacper Gunia
 
PDF
Advanced symfony Techniques
Kris Wallsmith
 
PDF
PHPSpec - the only Design Tool you need - 4Developers
Kacper Gunia
 
PDF
You Don't Know Query (WordCamp Netherlands 2012)
andrewnacin
 
PDF
PhpSpec 2.0 ilustrated by examples
Marcello Duarte
 
PPTX
Zero to SOLID
Vic Metcalfe
 
Hooks WCSD12
Jeffrey Zinn
 
Mocking Demystified
Marcello Duarte
 
Forget about Index.php and build you applications around HTTP - PHPers Cracow
Kacper Gunia
 
Advanced symfony Techniques
Kris Wallsmith
 
PHPSpec - the only Design Tool you need - 4Developers
Kacper Gunia
 
You Don't Know Query (WordCamp Netherlands 2012)
andrewnacin
 
PhpSpec 2.0 ilustrated by examples
Marcello Duarte
 
Zero to SOLID
Vic Metcalfe
 

What's hot (20)

PDF
Decoupling with Design Patterns and Symfony2 DIC
Konstantin Kudryashov
 
PDF
Design how your objects talk through mocking
Konstantin Kudryashov
 
PDF
Introducing Assetic: Asset Management for PHP 5.3
Kris Wallsmith
 
PDF
Nubilus Perl
Flavio Poletti
 
ODP
Rich domain model with symfony 2.5 and doctrine 2.5
Leonardo Proietti
 
PDF
New Symfony Tips & Tricks (SymfonyCon Paris 2015)
Javier Eguiluz
 
KEY
Perl Web Client
Flavio Poletti
 
PDF
Decoupling the Ulabox.com monolith. From CRUD to DDD
Aleix Vergés
 
PDF
The IoC Hydra - Dutch PHP Conference 2016
Kacper Gunia
 
PDF
Min-Maxing Software Costs - Laracon EU 2015
Konstantin Kudryashov
 
PPTX
Let's write secure Drupal code! DUG Belgium - 08/08/2019
Balázs Tatár
 
PDF
Virtual Madness @ Etsy
Nishan Subedi
 
PPTX
Let's write secure drupal code! - Drupal Camp Pannonia 2019
Balázs Tatár
 
PDF
Min-Maxing Software Costs
Konstantin Kudryashov
 
PDF
Mojolicious
Marcos Rebelo
 
PDF
Как получить чёрный пояс по WordPress?
Yevhen Kotelnytskyi
 
PDF
The IoC Hydra
Kacper Gunia
 
PDF
Как получить чёрный пояс по WordPress? v2.0
Yevhen Kotelnytskyi
 
PDF
Forget about index.php and build you applications around HTTP!
Kacper Gunia
 
KEY
CodeIgniter 3.0
Phil Sturgeon
 
Decoupling with Design Patterns and Symfony2 DIC
Konstantin Kudryashov
 
Design how your objects talk through mocking
Konstantin Kudryashov
 
Introducing Assetic: Asset Management for PHP 5.3
Kris Wallsmith
 
Nubilus Perl
Flavio Poletti
 
Rich domain model with symfony 2.5 and doctrine 2.5
Leonardo Proietti
 
New Symfony Tips & Tricks (SymfonyCon Paris 2015)
Javier Eguiluz
 
Perl Web Client
Flavio Poletti
 
Decoupling the Ulabox.com monolith. From CRUD to DDD
Aleix Vergés
 
The IoC Hydra - Dutch PHP Conference 2016
Kacper Gunia
 
Min-Maxing Software Costs - Laracon EU 2015
Konstantin Kudryashov
 
Let's write secure Drupal code! DUG Belgium - 08/08/2019
Balázs Tatár
 
Virtual Madness @ Etsy
Nishan Subedi
 
Let's write secure drupal code! - Drupal Camp Pannonia 2019
Balázs Tatár
 
Min-Maxing Software Costs
Konstantin Kudryashov
 
Mojolicious
Marcos Rebelo
 
Как получить чёрный пояс по WordPress?
Yevhen Kotelnytskyi
 
The IoC Hydra
Kacper Gunia
 
Как получить чёрный пояс по WordPress? v2.0
Yevhen Kotelnytskyi
 
Forget about index.php and build you applications around HTTP!
Kacper Gunia
 
CodeIgniter 3.0
Phil Sturgeon
 
Ad

Viewers also liked (20)

PPTX
Pertemuan 10
mutmainnamaruru
 
PDF
Comics and health education un’opportunità per promuovere la salute
Giuseppe Fattori
 
PPT
Длиннее, короче
МКОУ СОШ № 1 г. Сим
 
PPTX
Slide idea
Clare Huang
 
PPT
Establishing conclusive proof in Forensic Data Analytics
Gabriel Hopmans
 
PDF
Bellingham Real Estate - Buying, Selling or Questions?
Rich Johnson
 
PDF
Bellingham, Washington Waterfront
Rich Johnson
 
PPT
Звуки в словах
МКОУ СОШ № 1 г. Сим
 
PPT
Письмо букв Зз. Урок 3
МКОУ СОШ № 1 г. Сим
 
PDF
1 final scheme & syllabus ist & 2nd semester for the academic session 2014-15
Mudit Garg
 
PPTX
Cyber safety 2014withlinks
kellieromine
 
PPTX
Pertemuan 12
mutmainnamaruru
 
PDF
Presentacion tema memoria v1
Camilo López Aravena
 
KEY
Haskell. Getting started (RU)
Kirill Zonov
 
PPT
Согласные звуки д, дь. Буквы Дд. Урок 1
МКОУ СОШ № 1 г. Сим
 
PDF
Exetastea didaktea ili_panelladika_exetazomenon_mathimatwn_g_lykeiou_2013_2014
Eleni Papadopoulou
 
PPT
Согласные звуки д, дь. Буквы Дд. Урок 2
МКОУ СОШ № 1 г. Сим
 
PPTX
Pertemuan 9
mutmainnamaruru
 
PPT
Kaunokirjallisuus ja hyvinvointi
sunnycesilia
 
PPTX
Pertemuan 1tiga
mutmainnamaruru
 
Pertemuan 10
mutmainnamaruru
 
Comics and health education un’opportunità per promuovere la salute
Giuseppe Fattori
 
Длиннее, короче
МКОУ СОШ № 1 г. Сим
 
Slide idea
Clare Huang
 
Establishing conclusive proof in Forensic Data Analytics
Gabriel Hopmans
 
Bellingham Real Estate - Buying, Selling or Questions?
Rich Johnson
 
Bellingham, Washington Waterfront
Rich Johnson
 
Звуки в словах
МКОУ СОШ № 1 г. Сим
 
Письмо букв Зз. Урок 3
МКОУ СОШ № 1 г. Сим
 
1 final scheme & syllabus ist & 2nd semester for the academic session 2014-15
Mudit Garg
 
Cyber safety 2014withlinks
kellieromine
 
Pertemuan 12
mutmainnamaruru
 
Presentacion tema memoria v1
Camilo López Aravena
 
Haskell. Getting started (RU)
Kirill Zonov
 
Согласные звуки д, дь. Буквы Дд. Урок 1
МКОУ СОШ № 1 г. Сим
 
Exetastea didaktea ili_panelladika_exetazomenon_mathimatwn_g_lykeiou_2013_2014
Eleni Papadopoulou
 
Согласные звуки д, дь. Буквы Дд. Урок 2
МКОУ СОШ № 1 г. Сим
 
Pertemuan 9
mutmainnamaruru
 
Kaunokirjallisuus ja hyvinvointi
sunnycesilia
 
Pertemuan 1tiga
mutmainnamaruru
 
Ad

Similar to WCLV13 JavaScript (20)

PDF
WCLA12 JavaScript
Jeffrey Zinn
 
PDF
Laying the proper foundation for plugin and theme development
Tammy Hart
 
PDF
Avinash Kundaliya: Javascript and WordPress
wpnepal
 
PDF
Seven deadly theming sins
George Stephanis
 
PDF
Developing WordPress Plugins : For Begineers
M A Hossain Tonu
 
PPTX
Introduction to Plugin Programming, WordCamp Miami 2011
David Carr
 
PDF
WordPress Plugin Development 201
ylefebvre
 
PPTX
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
arcware
 
PDF
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
WordCamp Sydney
 
KEY
Wp and jq
Digitally
 
PPTX
WordPress Structure and Best Practices
markparolisi
 
PPT
WordPress and Ajax
Ronald Huereca
 
PDF
Plugin Development @ WordCamp Norway 2014
Barry Kooij
 
PDF
A WordPress workshop at Cefalo
Beroza Paul
 
PDF
JavaScript & AJAX in WordPress
Igor Benić
 
ODP
Building your first WordPress plugin
Justin Foell
 
PDF
WordPress plugin development
Luc De Brouwer
 
PDF
5 年後還是新手 - WordPress Plugin 開發大冒險 - GOTY
William Chong
 
PPTX
WordPress Plugin Development
Adam Englander
 
PDF
WordPress customizer: for themes and more
R-Cubed Design Forge
 
WCLA12 JavaScript
Jeffrey Zinn
 
Laying the proper foundation for plugin and theme development
Tammy Hart
 
Avinash Kundaliya: Javascript and WordPress
wpnepal
 
Seven deadly theming sins
George Stephanis
 
Developing WordPress Plugins : For Begineers
M A Hossain Tonu
 
Introduction to Plugin Programming, WordCamp Miami 2011
David Carr
 
WordPress Plugin Development 201
ylefebvre
 
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
arcware
 
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
WordCamp Sydney
 
Wp and jq
Digitally
 
WordPress Structure and Best Practices
markparolisi
 
WordPress and Ajax
Ronald Huereca
 
Plugin Development @ WordCamp Norway 2014
Barry Kooij
 
A WordPress workshop at Cefalo
Beroza Paul
 
JavaScript & AJAX in WordPress
Igor Benić
 
Building your first WordPress plugin
Justin Foell
 
WordPress plugin development
Luc De Brouwer
 
5 年後還是新手 - WordPress Plugin 開發大冒險 - GOTY
William Chong
 
WordPress Plugin Development
Adam Englander
 
WordPress customizer: for themes and more
R-Cubed Design Forge
 

Recently uploaded (20)

PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
CIFDAQ's Token Spotlight: SKY - A Forgotten Giant's Comeback?
CIFDAQ
 
PDF
GYTPOL If You Give a Hacker a Host
linda296484
 
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
georgschmitzdoerner
 
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
PDF
This slide provides an overview Technology
mineshkharadi333
 
PDF
DevOps & Developer Experience Summer BBQ
AUGNYC
 
PDF
Make GenAI investments go further with the Dell AI Factory - Infographic
Principled Technologies
 
PDF
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
PDF
Google’s NotebookLM Unveils Video Overviews
SOFTTECHHUB
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
CIFDAQ's Token Spotlight: SKY - A Forgotten Giant's Comeback?
CIFDAQ
 
GYTPOL If You Give a Hacker a Host
linda296484
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
madgavkar20181017ppt McKinsey Presentation.pdf
georgschmitzdoerner
 
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
This slide provides an overview Technology
mineshkharadi333
 
DevOps & Developer Experience Summer BBQ
AUGNYC
 
Make GenAI investments go further with the Dell AI Factory - Infographic
Principled Technologies
 
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
Google’s NotebookLM Unveils Video Overviews
SOFTTECHHUB
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 

WCLV13 JavaScript

  • 1. Weaving JavaScript -- in and out of -- WordPress WordCamp Las Vegas 2013 slides: http://www.slideshare.net/jeffreyzinn/wclv13-javascript code: https://gist.github.com/jeffreyzinn/7953881 Friday, December 13, 13
  • 2. Jeffrey Zinn • Co-founder of Pixel Jar • WordCamp OC co-organizer • AdSanity co-developer • @jeffreyzinn • [email protected] surfer, WordPress fanboy, avid backpacker, euro gamer, soccer hooligan, traveler, voracious coffee drinker Friday, December 13, 13
  • 3. Need To Know 1. JavaScript 2. Functions 3. Actions Friday, December 13, 13
  • 4. Topics 1. Loading JavaScripts - making JavaScripts available to themes, plugins and code 2. Available Libraries - JavaScripts that are already available in a default WordPress installation 3. Using CDNs - load JavaScripts from nonlocal sources 4. Localize Script - making data from PHP available in JavaScript Friday, December 13, 13
  • 5. 1. Loading Javascript making JavaScripts available to themes, plugins and code Friday, December 13, 13
  • 6. Example 1 What we are doing: Load a custom JavaScript called custom.js from my theme’s /js directory. load me Friday, December 13, 13
  • 7. Do Not... ...simply add a <script> tag into a template or header file <head profile="http://gmpg.org/xfn/11"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>WP Starter Setup — Just another WordPress site</title> <link rel="stylesheet" href="http://wp.start/wp-content/ themes/billerickson-BE-Genesis-Child-c73d97a/style.css" type="text/css" media="screen" /> <script type='text/javascript' src='http://wp.start/wpincludes/js/jquery/jquery.js?ver=1.7.2'></script> <script type="text/javascript" src="http://wp.start/wpcontent/themes/billerickson-BE-Genesis-Child-c73d97a/js/ custom.js"></script> </head> Friday, December 13, 13
  • 8. Do Not... ...echo out a <script> tag using using the wp_head/wp_footer action <?php add_action( 'wp_head', 'load_my_script' ); function load_my_script() { $src = get_stylesheet_directory_uri() . '/js/custom.js’; echo '<script type="text/javascript" src="' . $src . '”></script>'; } ?>  Friday, December 13, 13
  • 9. Functions • wp_register_script() - get ready to use a script (but don’t load it up just yet) • wp_deregister_script() - remove a registered script • wp_enqueue_script() - load that script into my theme/plugin so I can use it • wp_dequeue_script() - remove an enqueued script Friday, December 13, 13
  • 10. The Process 1. Use the wp_enqueue_scripts action to load in your selected JavaScripts 2. Stage a script by calling the wp_register_script function 3. Load the script from #2 using the wp_enqueue_script function Often on functions.php, but could be elsewhere in your theme or plugin code. Friday, December 13, 13
  • 11. wp_register_script() Description: Safe way of registering JavaScripts in WordPress for later use: <?php  wp_register_script ( $handle, $src, $deps, $ver, $in_footer ); ?> string string array string boolean give the file a unique nickname (required) Friday, December 13, 13 where is the file what other files have to be loaded first the script’s version number should WP try and load this in the footer
  • 12. wp_register_script() Description: Safe way of registering JavaScripts in WordPress for later use: <?php  wp_register_script ( $handle, $src, $deps, $ver, $in_footer ); ?> string string array string boolean Note: admin_enqueue_scripts to call it on the admin side, or use login_enqueue_scripts for login screens. Friday, December 13, 13
  • 13. Example 1.1 What we are doing: Load a custom JavaScript called custom.js from my theme’s /js directory. <?php  add_action( 'wp_enqueue_scripts', 'simple_load_script' ); function simple_load_script() { $src = get_stylesheet_directory_uri() . '/js/custom.js' ; wp_register_script( 'custom-script', $src, array( 'jquery' ), '1', TRUE ); } ?>  wp_enqueue_script( 'custom-script' ); Friday, December 13, 13
  • 14. Example 1.2 What we are doing: Register and enqueue custom.js as separate actions. <?php  /** Register JavaScripts **/ add_action( 'wp_enqueue_scripts', 'custom_register_scripts' ); function custom_register_scripts() { $src = get_stylesheet_directory_uri() . '/js/custom.js' ; wp_register_script( 'custom-script', $src, array( 'jquery' ), '1', TRUE ); } /** Enqueue JavaScripts **/ add_action( 'wp_enqueue_scripts', 'custom_enqueue_scripts' ); function custom_enqueue_scripts() { wp_enqueue_script( 'custom-script' ); } ?>  Friday, December 13, 13
  • 15. Example 1.3 What we are doing: Load custom.js conditionally for pages only. <?php  add_action( 'wp_enqueue_scripts', 'custom_script_for_pages' ); function custom_script_for_pages() { $src = get_stylesheet_directory_uri() . '/js/custom.js' ; wp_register_script( 'custom-script', $src, array( 'jquery' ), '1', TRUE ); } ?>  if( is_page() ) wp_enqueue_script( 'custom-script' ); Friday, December 13, 13
  • 16. Example 1.4 What we are doing: Load custom.js without registering. <?php  add_action( 'wp_enqueue_scripts', 'custom_script_enqueue' ); function custom_script_enqueue() { $src = get_stylesheet_directory_uri() . '/js/custom.js' ; wp_enqueue_script( 'custom-script', $src, array( 'jquery' ), '1', TRUE ); } ?>  Friday, December 13, 13
  • 17. (works with styles too) • wp_register_style() • wp_deregister_style() • wp_enqueue_style() • wp_dequeue_style() Friday, December 13, 13
  • 18. 2. Available Libraries JavaScripts that are already available in a default WordPress installation Friday, December 13, 13
  • 19. Available Libraries Script Handle SWFUpload swfupload jQuery UI Core jquery-ui-core jQuery UI Accordion jquery-ui-accordion jQuery UI Datepicker jquery-ui-datepicker ThickBox thickbox jQuery Hotkeys jquery-hotkeys ...plus many other scripts http://codex.wordpress.org/Function_Reference/ wp_enqueue_script#Default_scripts_included_with_WordPress Friday, December 13, 13
  • 20. Example 2.1 What we are doing: Load and use jQuery UI Draggable, which is preregistered. <?php  add_action( 'wp_enqueue_scripts', 'enqueue_draggable' ); function enqueue_draggable() { wp_enqueue_script( 'jquery-ui-draggable' ); } ?>  Friday, December 13, 13
  • 21. Example 2.2 What we are doing: Load a custom script called draggable.js in /js directory that uses jQuery UI Draggable and make our widgets draggable! <?php  /** Corresponding JavaScript: https://gist.github.com/3718542 **/ add_action( 'wp_enqueue_scripts', 'custom_draggable_script' ); function custom_draggable_script() { $src = get_stylesheet_directory_uri() . '/js/draggable.js' ; wp_register_script( 'custom-draggable-script', $src, array( 'jquery','jquery-ui-draggable' ), '1', TRUE ); wp_enqueue_script( 'custom-draggable-script' ); } ?>  Friday, December 13, 13
  • 22. 3. Using CDNs load JavaScripts from non-local sources Friday, December 13, 13
  • 23. Example 3.1 What we are doing: Load jquery from an external source. <?php  add_action( 'wp_enqueue_scripts', 'load_jquery_from_googleapis' ); function load_jquery_from_googleapis() { wp_deregister_script( 'jquery' ); $src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'; wp_register_script( 'jquery', $src, array(), '1.10.2' ); wp_enqueue_script( 'jquery' ); } ?>  Friday, December 13, 13
  • 24. Example 3.1 What we are doing: Load jQuery from an external source. <?php  add_action( 'wp_enqueue_scripts', 'load_jquery_from_googleapis' ); function load_jquery_from_googleapis() { wp_deregister_script( 'jquery' ); $src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'; wp_register_script( 'jquery', $src, array(), '1.10.2' ); wp_enqueue_script( 'jquery' ); } ?>  Friday, December 13, 13 Keep same handle for dependencies
  • 25. Example 3.1 What we are doing: Load jquery from an external source. <?php  add_action( 'wp_enqueue_scripts', 'load_jquery_from_googleapis' ); function load_jquery_from_googleapis() { wp_deregister_script( 'jquery' ); $src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'; wp_register_script( 'jquery', $src, array(), '1.10.2' ); wp_enqueue_script( 'jquery' ); } ?>  Friday, December 13, 13 Be careful of version #, is it still compatible with WP and your stuff?
  • 26. 4. Localize Script making data from PHP available in JavaScript Friday, December 13, 13
  • 27. Do Not... ...use PHP to build JavaScript code <?php add_action( 'wp_head', 'build_my_script' ); function build_my_script() { global $current_user; get_currentuserinfo(); echo echo "rn"; '<script type="text/javascript">' . "rn"; echo "t" . 'var userid = "' . esc_js( $current_user->ID ) . '";'; echo "rn"; echo "t" . 'var fname = "' . esc_js( $current_user->user_firstname ) . '";'; echo "rn"; echo '</script>' . "rn"; } ?>  Friday, December 13, 13
  • 28. wp_localize_script() Description: Send PHP data into the JavaScript data world. Usage: <?php  wp_localize_script( $handle, $object_name, $l10n );  ?> string string array nickname of script to send data to (required) Friday, December 13, 13 what to call the object when it is in the script (required) what data to send to the script (required)
  • 29. wp_localize_script() Description: Send PHP data into the JavaScript data world. Usage: <?php  wp_localize_script( $handle, $object_name, $l10n );  ?> Note: wp_localize_script() must be called AFTER the script it's being attached to has been enqueued. It doesn't put the localized script in a queue for later queued scripts. Friday, December 13, 13
  • 30. wp_localize_script() Description: Send PHP data into the JavaScript data world. Usage: <?php  wp_localize_script( $handle, $object_name, $l10n );  ?> Also Note: $l10n (array) (required) The data itself. The data can be either a single or multi (as of 3.3) dimensional array. Friday, December 13, 13
  • 31. Example 4.1 What we are doing: Send user ID and first name from PHP over to custom.js and alert the user. <?php /** Corresponding JavaScript: https://gist.github.com/3718839 **/ add_action( 'wp_enqueue_scripts', 'send_user_data_to_custom' ); function send_user_data_to_custom() { $src = get_stylesheet_directory_uri() . '/js/custom.js' ; wp_register_script( 'custom-script', $src, array( 'jquery' ), '1', TRUE ); wp_enqueue_script( 'custom-script' ); global $current_user; get_currentuserinfo(); $data = array(  'userid' => $current_user->ID, 'fname'  => $current_user->user_firstname ); } ?>  wp_localize_script( 'custom-script', 'userinfo', $data ); Friday, December 13, 13
  • 32. Example 4.1 What we are doing: Send user ID and first name from PHP over to custom.js and alert the user. <?php /** Corresponding JavaScript: https://gist.github.com/3718839 **/ add_action( 'wp_enqueue_scripts', 'send_user_data_to_custom' ); in JavaScript the data can be called by function send_user_data_to_custom() { userinfo.userid and userinfo.fname using $src = get_stylesheet_directory_uri() . '/js/custom.js' ; wp_register_script( 'custom-script', $src, array( 'jquery' ), '1', TRUE ); wp_enqueue_script( 'custom-script' ); + global $current_user; get_currentuserinfo(); $data = array(  'userid' => $current_user->ID, 'fname'  => $current_user->user_firstname ); } ?>  wp_localize_script( 'custom-script', 'userinfo', $data ); Friday, December 13, 13
  • 33. Example 4.1 JavaScript: custom.js jQuery(document).ready(function($){ alert("Hey, " + userinfo.fname + ", your user ID is " + userinfo.userid + ". Boom!"); }); Friday, December 13, 13
  • 34. questions? (thanks!) WordCamp Las Vegas 2013 slides: http://www.slideshare.net/jeffreyzinn/wclv13-javascript code: https://gist.github.com/jeffreyzinn/7953881 Friday, December 13, 13