SlideShare ist ein Scribd-Unternehmen logo
1 von 33
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

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

Was ist angesagt? (20)

Decoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DICDecoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DIC
 
Design how your objects talk through mocking
Design how your objects talk through mockingDesign how your objects talk through mocking
Design how your objects talk through mocking
 
Introducing Assetic: Asset Management for PHP 5.3
Introducing Assetic: Asset Management for PHP 5.3Introducing Assetic: Asset Management for PHP 5.3
Introducing Assetic: Asset Management for PHP 5.3
 
Nubilus Perl
Nubilus PerlNubilus Perl
Nubilus Perl
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
 
New Symfony Tips & Tricks (SymfonyCon Paris 2015)
New Symfony Tips & Tricks (SymfonyCon Paris 2015)New Symfony Tips & Tricks (SymfonyCon Paris 2015)
New Symfony Tips & Tricks (SymfonyCon Paris 2015)
 
Perl Web Client
Perl Web ClientPerl Web Client
Perl Web Client
 
Decoupling the Ulabox.com monolith. From CRUD to DDD
Decoupling the Ulabox.com monolith. From CRUD to DDDDecoupling the Ulabox.com monolith. From CRUD to DDD
Decoupling the Ulabox.com monolith. From CRUD to DDD
 
The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016
 
Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015
 
Let's write secure Drupal code! DUG Belgium - 08/08/2019
Let's write secure Drupal code! DUG Belgium - 08/08/2019Let's write secure Drupal code! DUG Belgium - 08/08/2019
Let's write secure Drupal code! DUG Belgium - 08/08/2019
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
Let's write secure drupal code! - Drupal Camp Pannonia 2019
Let's write secure drupal code! - Drupal Camp Pannonia 2019Let's write secure drupal code! - Drupal Camp Pannonia 2019
Let's write secure drupal code! - Drupal Camp Pannonia 2019
 
Min-Maxing Software Costs
Min-Maxing Software CostsMin-Maxing Software Costs
Min-Maxing Software Costs
 
Mojolicious
MojoliciousMojolicious
Mojolicious
 
Как получить чёрный пояс по WordPress?
Как получить чёрный пояс по WordPress?Как получить чёрный пояс по WordPress?
Как получить чёрный пояс по WordPress?
 
The IoC Hydra
The IoC HydraThe IoC Hydra
The IoC Hydra
 
Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0
 
Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!
 
CodeIgniter 3.0
CodeIgniter 3.0CodeIgniter 3.0
CodeIgniter 3.0
 

Andere mochten auch

Comics and health education un’opportunità per promuovere la salute
Comics and health education  un’opportunità per promuovere la salute Comics and health education  un’opportunità per promuovere la salute
Comics and health education un’opportunità per promuovere la salute Giuseppe Fattori
 
Establishing conclusive proof in Forensic Data Analytics
Establishing conclusive proof in Forensic Data AnalyticsEstablishing conclusive proof in Forensic Data Analytics
Establishing conclusive proof in Forensic Data AnalyticsGabriel Hopmans
 
Bellingham Real Estate - Buying, Selling or Questions?
Bellingham Real Estate - Buying, Selling or Questions?Bellingham Real Estate - Buying, Selling or Questions?
Bellingham Real Estate - Buying, Selling or Questions?Rich Johnson
 
Bellingham, Washington Waterfront
Bellingham, Washington Waterfront Bellingham, Washington Waterfront
Bellingham, Washington Waterfront Rich Johnson
 
1 final scheme & syllabus ist & 2nd semester for the academic session 2014-15
1 final scheme & syllabus  ist & 2nd semester for the academic session 2014-151 final scheme & syllabus  ist & 2nd semester for the academic session 2014-15
1 final scheme & syllabus ist & 2nd semester for the academic session 2014-15Mudit Garg
 
Cyber safety 2014withlinks
Cyber safety 2014withlinksCyber safety 2014withlinks
Cyber safety 2014withlinkskellieromine
 
Haskell. Getting started (RU)
Haskell. Getting started (RU)Haskell. Getting started (RU)
Haskell. Getting started (RU)Kirill Zonov
 
Согласные звуки д, дь. Буквы Дд. Урок 1
Согласные звуки д, дь. Буквы Дд. Урок 1Согласные звуки д, дь. Буквы Дд. Урок 1
Согласные звуки д, дь. Буквы Дд. Урок 1МКОУ СОШ № 1 г. Сим
 
Exetastea didaktea ili_panelladika_exetazomenon_mathimatwn_g_lykeiou_2013_2014
Exetastea didaktea ili_panelladika_exetazomenon_mathimatwn_g_lykeiou_2013_2014Exetastea didaktea ili_panelladika_exetazomenon_mathimatwn_g_lykeiou_2013_2014
Exetastea didaktea ili_panelladika_exetazomenon_mathimatwn_g_lykeiou_2013_2014Eleni Papadopoulou
 
Согласные звуки д, дь. Буквы Дд. Урок 2
Согласные звуки д, дь. Буквы Дд. Урок 2Согласные звуки д, дь. Буквы Дд. Урок 2
Согласные звуки д, дь. Буквы Дд. Урок 2МКОУ СОШ № 1 г. Сим
 
Kaunokirjallisuus ja hyvinvointi
Kaunokirjallisuus ja hyvinvointiKaunokirjallisuus ja hyvinvointi
Kaunokirjallisuus ja hyvinvointisunnycesilia
 

Andere mochten auch (20)

Pertemuan 10
Pertemuan 10Pertemuan 10
Pertemuan 10
 
Comics and health education un’opportunità per promuovere la salute
Comics and health education  un’opportunità per promuovere la salute Comics and health education  un’opportunità per promuovere la salute
Comics and health education un’opportunità per promuovere la salute
 
Длиннее, короче
Длиннее, корочеДлиннее, короче
Длиннее, короче
 
Slide idea
Slide ideaSlide idea
Slide idea
 
Establishing conclusive proof in Forensic Data Analytics
Establishing conclusive proof in Forensic Data AnalyticsEstablishing conclusive proof in Forensic Data Analytics
Establishing conclusive proof in Forensic Data Analytics
 
Bellingham Real Estate - Buying, Selling or Questions?
Bellingham Real Estate - Buying, Selling or Questions?Bellingham Real Estate - Buying, Selling or Questions?
Bellingham Real Estate - Buying, Selling or Questions?
 
Bellingham, Washington Waterfront
Bellingham, Washington Waterfront Bellingham, Washington Waterfront
Bellingham, Washington Waterfront
 
Звуки в словах
Звуки в словахЗвуки в словах
Звуки в словах
 
Письмо букв Зз. Урок 3
Письмо букв Зз. Урок 3Письмо букв Зз. Урок 3
Письмо букв Зз. Урок 3
 
1 final scheme & syllabus ist & 2nd semester for the academic session 2014-15
1 final scheme & syllabus  ist & 2nd semester for the academic session 2014-151 final scheme & syllabus  ist & 2nd semester for the academic session 2014-15
1 final scheme & syllabus ist & 2nd semester for the academic session 2014-15
 
Cyber safety 2014withlinks
Cyber safety 2014withlinksCyber safety 2014withlinks
Cyber safety 2014withlinks
 
Pertemuan 12
Pertemuan 12Pertemuan 12
Pertemuan 12
 
Presentacion tema memoria v1
Presentacion tema memoria v1Presentacion tema memoria v1
Presentacion tema memoria v1
 
Haskell. Getting started (RU)
Haskell. Getting started (RU)Haskell. Getting started (RU)
Haskell. Getting started (RU)
 
Согласные звуки д, дь. Буквы Дд. Урок 1
Согласные звуки д, дь. Буквы Дд. Урок 1Согласные звуки д, дь. Буквы Дд. Урок 1
Согласные звуки д, дь. Буквы Дд. Урок 1
 
Exetastea didaktea ili_panelladika_exetazomenon_mathimatwn_g_lykeiou_2013_2014
Exetastea didaktea ili_panelladika_exetazomenon_mathimatwn_g_lykeiou_2013_2014Exetastea didaktea ili_panelladika_exetazomenon_mathimatwn_g_lykeiou_2013_2014
Exetastea didaktea ili_panelladika_exetazomenon_mathimatwn_g_lykeiou_2013_2014
 
Согласные звуки д, дь. Буквы Дд. Урок 2
Согласные звуки д, дь. Буквы Дд. Урок 2Согласные звуки д, дь. Буквы Дд. Урок 2
Согласные звуки д, дь. Буквы Дд. Урок 2
 
Pertemuan 9
Pertemuan 9Pertemuan 9
Pertemuan 9
 
Kaunokirjallisuus ja hyvinvointi
Kaunokirjallisuus ja hyvinvointiKaunokirjallisuus ja hyvinvointi
Kaunokirjallisuus ja hyvinvointi
 
Pertemuan 1tiga
Pertemuan 1tigaPertemuan 1tiga
Pertemuan 1tiga
 

Ähnlich wie WCLV13 JavaScript

Developers, Be a Bada$$ with WP-CLI
Developers, Be a Bada$$ with WP-CLIDevelopers, Be a Bada$$ with WP-CLI
Developers, Be a Bada$$ with WP-CLIWP Engine
 
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)arcware
 
Flash Widget Tutorial
Flash Widget TutorialFlash Widget Tutorial
Flash Widget Tutorialhussulinux
 
Manage WordPress with Awesome using wp cli
Manage WordPress with Awesome using wp cliManage WordPress with Awesome using wp cli
Manage WordPress with Awesome using wp cliGetSource
 
WordCamp Vancouver 2012 - Manage WordPress with Awesome using wp-cli
WordCamp Vancouver 2012 - Manage WordPress with Awesome using wp-cliWordCamp Vancouver 2012 - Manage WordPress with Awesome using wp-cli
WordCamp Vancouver 2012 - Manage WordPress with Awesome using wp-cliGetSource
 
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...tdc-globalcode
 
Web development automatisation for fun and profit (Artem Daniliants)
Web development automatisation for fun and profit (Artem Daniliants)Web development automatisation for fun and profit (Artem Daniliants)
Web development automatisation for fun and profit (Artem Daniliants)LumoSpark
 
Guia de Sobrevivência JS no mundo Open Source
Guia de Sobrevivência JS no mundo Open SourceGuia de Sobrevivência JS no mundo Open Source
Guia de Sobrevivência JS no mundo Open SourceLeonardo Balter
 
WordPress Plugin development
WordPress Plugin developmentWordPress Plugin development
WordPress Plugin developmentMostafa Soufi
 
High Performance XQuery Processing in PHP with Zorba by Vikram Vaswani
High Performance XQuery Processing in PHP with Zorba by Vikram VaswaniHigh Performance XQuery Processing in PHP with Zorba by Vikram Vaswani
High Performance XQuery Processing in PHP with Zorba by Vikram Vaswanivvaswani
 
Laying the proper foundation for plugin and theme development
Laying the proper foundation for plugin and theme developmentLaying the proper foundation for plugin and theme development
Laying the proper foundation for plugin and theme developmentTammy Hart
 
JavaScript & AJAX in WordPress
JavaScript & AJAX in WordPressJavaScript & AJAX in WordPress
JavaScript & AJAX in WordPressIgor Benić
 
[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress Development[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress DevelopmentAdam Tomat
 
RoR 101: Session 6
RoR 101: Session 6RoR 101: Session 6
RoR 101: Session 6Rory Gianni
 
Fix me if you can - DrupalCon prague
Fix me if you can - DrupalCon pragueFix me if you can - DrupalCon prague
Fix me if you can - DrupalCon praguehernanibf
 
Vagrant WordCamp Hamilton
Vagrant  WordCamp HamiltonVagrant  WordCamp Hamilton
Vagrant WordCamp HamiltonPaul Bearne
 

Ähnlich wie WCLV13 JavaScript (20)

WCLA12 JavaScript
WCLA12 JavaScriptWCLA12 JavaScript
WCLA12 JavaScript
 
Developers, Be a Bada$$ with WP-CLI
Developers, Be a Bada$$ with WP-CLIDevelopers, Be a Bada$$ with WP-CLI
Developers, Be a Bada$$ with WP-CLI
 
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
 
Flash Widget Tutorial
Flash Widget TutorialFlash Widget Tutorial
Flash Widget Tutorial
 
Manage WordPress with Awesome using wp cli
Manage WordPress with Awesome using wp cliManage WordPress with Awesome using wp cli
Manage WordPress with Awesome using wp cli
 
WordCamp Vancouver 2012 - Manage WordPress with Awesome using wp-cli
WordCamp Vancouver 2012 - Manage WordPress with Awesome using wp-cliWordCamp Vancouver 2012 - Manage WordPress with Awesome using wp-cli
WordCamp Vancouver 2012 - Manage WordPress with Awesome using wp-cli
 
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
 
Web development automatisation for fun and profit (Artem Daniliants)
Web development automatisation for fun and profit (Artem Daniliants)Web development automatisation for fun and profit (Artem Daniliants)
Web development automatisation for fun and profit (Artem Daniliants)
 
Guia de Sobrevivência JS no mundo Open Source
Guia de Sobrevivência JS no mundo Open SourceGuia de Sobrevivência JS no mundo Open Source
Guia de Sobrevivência JS no mundo Open Source
 
WordPress Plugin development
WordPress Plugin developmentWordPress Plugin development
WordPress Plugin development
 
WPDay Bologna 2013
WPDay Bologna 2013WPDay Bologna 2013
WPDay Bologna 2013
 
High Performance XQuery Processing in PHP with Zorba by Vikram Vaswani
High Performance XQuery Processing in PHP with Zorba by Vikram VaswaniHigh Performance XQuery Processing in PHP with Zorba by Vikram Vaswani
High Performance XQuery Processing in PHP with Zorba by Vikram Vaswani
 
Laying the proper foundation for plugin and theme development
Laying the proper foundation for plugin and theme developmentLaying the proper foundation for plugin and theme development
Laying the proper foundation for plugin and theme development
 
JavaScript & AJAX in WordPress
JavaScript & AJAX in WordPressJavaScript & AJAX in WordPress
JavaScript & AJAX in WordPress
 
[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress Development[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress Development
 
RoR 101: Session 6
RoR 101: Session 6RoR 101: Session 6
RoR 101: Session 6
 
Fix me if you can - DrupalCon prague
Fix me if you can - DrupalCon pragueFix me if you can - DrupalCon prague
Fix me if you can - DrupalCon prague
 
New PHP Exploitation Techniques
New PHP Exploitation TechniquesNew PHP Exploitation Techniques
New PHP Exploitation Techniques
 
Vagrant WordCamp Hamilton
Vagrant  WordCamp HamiltonVagrant  WordCamp Hamilton
Vagrant WordCamp Hamilton
 
Webpack
Webpack Webpack
Webpack
 

Kürzlich hochgeladen

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 

Kürzlich hochgeladen (20)

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

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 • jeff@jzinn.us 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