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

             WordPress
     WordCamp Los Angeles 2012

slides: http://www.slideshare.net/jeffreyzinn/wcla12-javascript
              code: https://gist.github.com/3718135
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
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 non-
   local sources
4. Localize Script - making data from PHP
   available in JavaScript
1. Loading Javascript
making JavaScripts available to themes,
          plugins and code
Example 1
What we are doing:
Load a custom JavaScript called custom.js from
my theme’s /js directory.




                                     load
                                       me
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/wp-
  includes/js/jquery/jquery.js?ver=1.7.2'></script>
  <script type="text/javascript" src="http://wp.start/wp-
  content/themes/billerickson-BE-Genesis-Child-c73d97a/js/
  custom.js"></script>
</head>
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>';

}
?> 
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
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.
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   where is   what other       the       should WP
        a unique     the file    files have to   script’s   try and load
       nickname                  be loaded     version     this in the
      (required)                    first       number        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.
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' );
}
?> 
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' );

}
?> 
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' );
}
?> 
2. Available Libraries
JavaScripts that are already available in
    a default WordPress installation
Available Libraries
         Script                         Handle
Scriptaculous Root               scriptaculous-root
     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 64 other scripts
      http://codex.wordpress.org/Function_Reference/
 wp_enqueue_script#Default_scripts_included_with_WordPress
Example 2.1
What we are doing:
Load and use jQuery UI Draggable, which is pre-
registered, and make our widgets draggable!


<?php 
add_action( 'wp_enqueue_scripts', 'enqueue_draggable' );
function enqueue_draggable() {

      wp_enqueue_script( 'jquery-ui-draggable' );

}
?> 
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' );

}

?> 
3. Using CDNs
load JavaScripts from non-local sources
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.7.2/jquery.min.js';
      wp_register_script( 'jquery', $src, array(), '1.7.2' );

      wp_enqueue_script( 'jquery' );

}
?> 
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.7.2/jquery.min.js';
      wp_register_script( 'jquery', $src, array(), '1.7.2' );

      wp_enqueue_script( 'jquery' );

}
?>                      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.7.2/jquery.min.js';
      wp_register_script( 'jquery', $src, array(), '1.7.2' );

      wp_enqueue_script( 'jquery' );
                                           Be careful of version #,
}
?>                                         is it still compatible with
                                           WP and your stuff?
4. Localize Script
  making data from PHP
  available in JavaScript
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  "rn";
      echo  '<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";

}
?> 
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       what to call    what data
                        of script to    the object     to send to
                       send data to     when it is     the script
                        (required)     in the script   (required)
                                        (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.
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.
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 );
}
?> 
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     **/

                         in JavaScript the data can be called by
add_action( 'wp_enqueue_scripts', 'send_user_data_to_custom' );    using
function send_user_data_to_custom() {
                         userinfo.userid and userinfo.fname
      $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 );
}
?> 
Example 4.1
JavaScript: custom.js
jQuery(document).ready(function($){
    alert("Hey, " + userinfo.fname + ", your user ID is " + userinfo.userid + ". Boom!");
});
questions?
                          (thanks!)

slides: http://www.slideshare.net/jeffreyzinn/wcla12-javascript
              code: https://gist.github.com/3718135

More Related Content

What's hot (20)

PDF
Introduction to Vue.js
Meir Rotstein
 
PDF
Enjoy the vue.js
TechExeter
 
PDF
Difference between java script and jquery
Umar Ali
 
PPT
Symfony2 and AngularJS
Antonio Peric-Mazar
 
PDF
Sane Async Patterns
TrevorBurnham
 
PDF
Introduction to AngularJS For WordPress Developers
Caldera Labs
 
PPTX
How to Build SPA with Vue Router 2.0
Takuya Tejima
 
PPTX
Making Magento flying like a rocket! (A set of valuable tips for developers)
Ivan Chepurnyi
 
PDF
20130528 solution linux_frousseau_nopain_webdev
Frank Rousseau
 
PDF
Better Testing With PHP Unit
sitecrafting
 
PPT
Creating the interfaces of the future with the APIs of today
gerbille
 
PDF
Ajax Security
Joe Walker
 
PDF
Building a Startup Stack with AngularJS
FITC
 
KEY
#NewMeetup Performance
Justin Cataldo
 
PDF
Meetup Performance
Greg Whalin
 
PDF
2012.sandiego.wordcamp
Brandon Dove
 
PPTX
Effective C++/WinRT for UWP and Win32
Windows Developer
 
PDF
EWD 3 Training Course Part 38: Building a React.js application with QEWD, Part 4
Rob Tweed
 
PPTX
Introduction to Backbone.js & Marionette.js
Return on Intelligence
 
PPTX
IndexedDB - Querying and Performance
Parashuram N
 
Introduction to Vue.js
Meir Rotstein
 
Enjoy the vue.js
TechExeter
 
Difference between java script and jquery
Umar Ali
 
Symfony2 and AngularJS
Antonio Peric-Mazar
 
Sane Async Patterns
TrevorBurnham
 
Introduction to AngularJS For WordPress Developers
Caldera Labs
 
How to Build SPA with Vue Router 2.0
Takuya Tejima
 
Making Magento flying like a rocket! (A set of valuable tips for developers)
Ivan Chepurnyi
 
20130528 solution linux_frousseau_nopain_webdev
Frank Rousseau
 
Better Testing With PHP Unit
sitecrafting
 
Creating the interfaces of the future with the APIs of today
gerbille
 
Ajax Security
Joe Walker
 
Building a Startup Stack with AngularJS
FITC
 
#NewMeetup Performance
Justin Cataldo
 
Meetup Performance
Greg Whalin
 
2012.sandiego.wordcamp
Brandon Dove
 
Effective C++/WinRT for UWP and Win32
Windows Developer
 
EWD 3 Training Course Part 38: Building a React.js application with QEWD, Part 4
Rob Tweed
 
Introduction to Backbone.js & Marionette.js
Return on Intelligence
 
IndexedDB - Querying and Performance
Parashuram N
 

Viewers also liked (20)

PDF
Ashby regolamento ing_web
James LaFleur
 
DOC
Guia de calculo periodo 1
Jack Toloza
 
PPT
Christmas11 12
M. Carmen Cañadas
 
PPT
Письмо с. 21
МКОУ СОШ № 1 г. Сим
 
PPTX
The earth
svpp11
 
PPTX
Pertemuan 4
mutmainnamaruru
 
PPT
Письмо с. 22
МКОУ СОШ № 1 г. Сим
 
PPT
Письмо элементов
МКОУ СОШ № 1 г. Сим
 
PPTX
Rodohori
Eleni Papadopoulou
 
PPTX
Presentasi psi
Nadia Rahmatul Ummah
 
PPTX
Escape from Excel - Retail Can't Survive and Thrive on Spreadsheets
Jerry Inman
 
DOC
Programma filologou
Eleni Papadopoulou
 
PPTX
Jayanta Hazarika
Jayanta Hazarika
 
PDF
מהו צדק עברית2
taliaramati
 
PDF
Studio67 ref model
m2nd7
 
DOCX
το βιβλίο και ο υπολογιστής
Eleni Papadopoulou
 
PPTX
Ucronia
bjuanzuletaferrer
 
PPTX
выбираем будущую профессию
maychik1995
 
PPT
Input Output Devices (An Introduction)
Qsrealm
 
Ashby regolamento ing_web
James LaFleur
 
Guia de calculo periodo 1
Jack Toloza
 
Christmas11 12
M. Carmen Cañadas
 
The earth
svpp11
 
Pertemuan 4
mutmainnamaruru
 
Письмо элементов
МКОУ СОШ № 1 г. Сим
 
Presentasi psi
Nadia Rahmatul Ummah
 
Escape from Excel - Retail Can't Survive and Thrive on Spreadsheets
Jerry Inman
 
Programma filologou
Eleni Papadopoulou
 
Jayanta Hazarika
Jayanta Hazarika
 
מהו צדק עברית2
taliaramati
 
Studio67 ref model
m2nd7
 
το βιβλίο και ο υπολογιστής
Eleni Papadopoulou
 
выбираем будущую профессию
maychik1995
 
Input Output Devices (An Introduction)
Qsrealm
 
Ad

Similar to WCLA12 JavaScript (20)

PDF
WCLV13 JavaScript
Jeffrey Zinn
 
PDF
Laying the proper foundation for plugin and theme development
Tammy Hart
 
PDF
Seven deadly theming sins
George Stephanis
 
PDF
WordPress Plugin Development 201
ylefebvre
 
ODP
Building your first WordPress plugin
Justin Foell
 
PPTX
Introduction to Plugin Programming, WordCamp Miami 2011
David Carr
 
PDF
Avinash Kundaliya: Javascript and WordPress
wpnepal
 
PPT
WordPress and Ajax
Ronald Huereca
 
PDF
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
WordCamp Sydney
 
PPTX
WordPress Structure and Best Practices
markparolisi
 
PDF
So, You Wanna Dev? Join the Team! - WordCamp Raleigh 2017
Evan Mullins
 
PDF
Developing WordPress Plugins : For Begineers
M A Hossain Tonu
 
PDF
Bending word press to your will
Tom Jenkins
 
PDF
WordPress plugin development
Luc De Brouwer
 
PDF
5 年後還是新手 - WordPress Plugin 開發大冒險 - GOTY
William Chong
 
PDF
Plugin Development @ WordCamp Norway 2014
Barry Kooij
 
KEY
Wp and jq
Digitally
 
PPTX
WordPress Plugin Development
Adam Englander
 
PPTX
Simple Contact Us Plugin Development
wpnepal
 
PPTX
A peek into the world of WordPress plugin development
R-Cubed Design Forge
 
WCLV13 JavaScript
Jeffrey Zinn
 
Laying the proper foundation for plugin and theme development
Tammy Hart
 
Seven deadly theming sins
George Stephanis
 
WordPress Plugin Development 201
ylefebvre
 
Building your first WordPress plugin
Justin Foell
 
Introduction to Plugin Programming, WordCamp Miami 2011
David Carr
 
Avinash Kundaliya: Javascript and WordPress
wpnepal
 
WordPress and Ajax
Ronald Huereca
 
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
WordCamp Sydney
 
WordPress Structure and Best Practices
markparolisi
 
So, You Wanna Dev? Join the Team! - WordCamp Raleigh 2017
Evan Mullins
 
Developing WordPress Plugins : For Begineers
M A Hossain Tonu
 
Bending word press to your will
Tom Jenkins
 
WordPress plugin development
Luc De Brouwer
 
5 年後還是新手 - WordPress Plugin 開發大冒險 - GOTY
William Chong
 
Plugin Development @ WordCamp Norway 2014
Barry Kooij
 
Wp and jq
Digitally
 
WordPress Plugin Development
Adam Englander
 
Simple Contact Us Plugin Development
wpnepal
 
A peek into the world of WordPress plugin development
R-Cubed Design Forge
 
Ad

Recently uploaded (9)

PPTX
Understanding Emotional Intelligence: A Comprehensive Overview
siddharthjaan
 
PDF
The Story of Al-Fitra by Mr. Saidi Adam Younes
ademyounessaidi
 
PPTX
LESSON 1 IN PHILOSOPHY- INTRODUCTION TO PHILOSOPHY
MaimaiAlleraAcpal
 
PDF
UCSP-Quarter1_M5.pdf POLITICS AND POLITICL
jaredcagampan86
 
PDF
ExpoGestão 2025 - Networking – O Poder das Conexões Humanas
ExpoGestão
 
PPTX
AAM - NQAS Orientation CHALLANGES & SOLUTION 24 & 25 FEB24.pptx
minikashyap9528
 
PPTX
Free Preparation and Survival Apps that can save your life
Bob Mayer
 
PPTX
Impact_of_Power_Outages_Presentation.pptx
mansisingh27077
 
PPTX
Remote_Work_Productivity_Strategies.pptx
MuhammadUzair504018
 
Understanding Emotional Intelligence: A Comprehensive Overview
siddharthjaan
 
The Story of Al-Fitra by Mr. Saidi Adam Younes
ademyounessaidi
 
LESSON 1 IN PHILOSOPHY- INTRODUCTION TO PHILOSOPHY
MaimaiAlleraAcpal
 
UCSP-Quarter1_M5.pdf POLITICS AND POLITICL
jaredcagampan86
 
ExpoGestão 2025 - Networking – O Poder das Conexões Humanas
ExpoGestão
 
AAM - NQAS Orientation CHALLANGES & SOLUTION 24 & 25 FEB24.pptx
minikashyap9528
 
Free Preparation and Survival Apps that can save your life
Bob Mayer
 
Impact_of_Power_Outages_Presentation.pptx
mansisingh27077
 
Remote_Work_Productivity_Strategies.pptx
MuhammadUzair504018
 

WCLA12 JavaScript

  • 1. Weaving JavaScript -- in and out of -- WordPress WordCamp Los Angeles 2012 slides: http://www.slideshare.net/jeffreyzinn/wcla12-javascript code: https://gist.github.com/3718135
  • 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
  • 3. 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 non- local sources 4. Localize Script - making data from PHP available in JavaScript
  • 4. 1. Loading Javascript making JavaScripts available to themes, plugins and code
  • 5. Example 1 What we are doing: Load a custom JavaScript called custom.js from my theme’s /js directory. load me
  • 6. 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/wp- includes/js/jquery/jquery.js?ver=1.7.2'></script> <script type="text/javascript" src="http://wp.start/wp- content/themes/billerickson-BE-Genesis-Child-c73d97a/js/ custom.js"></script> </head>
  • 7. 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>'; } ?> 
  • 8. 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
  • 9. 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.
  • 10. 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 where is what other the should WP a unique the file files have to script’s try and load nickname be loaded version this in the (required) first number footer
  • 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 Note: admin_enqueue_scripts to call it on the admin side, or use login_enqueue_scripts for login screens.
  • 12. 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' ); } ?> 
  • 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' ); } ?> 
  • 14. 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' ); } ?> 
  • 15. 2. Available Libraries JavaScripts that are already available in a default WordPress installation
  • 16. Available Libraries Script Handle Scriptaculous Root scriptaculous-root 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 64 other scripts http://codex.wordpress.org/Function_Reference/ wp_enqueue_script#Default_scripts_included_with_WordPress
  • 17. Example 2.1 What we are doing: Load and use jQuery UI Draggable, which is pre- registered, and make our widgets draggable! <?php  add_action( 'wp_enqueue_scripts', 'enqueue_draggable' ); function enqueue_draggable() { wp_enqueue_script( 'jquery-ui-draggable' ); } ?> 
  • 18. 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' ); } ?> 
  • 19. 3. Using CDNs load JavaScripts from non-local sources
  • 20. 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.7.2/jquery.min.js'; wp_register_script( 'jquery', $src, array(), '1.7.2' ); wp_enqueue_script( 'jquery' ); } ?> 
  • 21. 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.7.2/jquery.min.js'; wp_register_script( 'jquery', $src, array(), '1.7.2' ); wp_enqueue_script( 'jquery' ); } ?>  Keep same handle for dependencies
  • 22. 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.7.2/jquery.min.js'; wp_register_script( 'jquery', $src, array(), '1.7.2' ); wp_enqueue_script( 'jquery' ); Be careful of version #, } ?>  is it still compatible with WP and your stuff?
  • 23. 4. Localize Script making data from PHP available in JavaScript
  • 24. 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 "rn"; echo '<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"; } ?> 
  • 25. 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 what to call what data of script to the object to send to send data to when it is the script (required) in the script (required) (required)
  • 26. 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.
  • 27. 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.
  • 28. 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 ); } ?> 
  • 29. 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 **/ in JavaScript the data can be called by add_action( 'wp_enqueue_scripts', 'send_user_data_to_custom' ); using function send_user_data_to_custom() { userinfo.userid and userinfo.fname $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 ); } ?> 
  • 30. Example 4.1 JavaScript: custom.js jQuery(document).ready(function($){ alert("Hey, " + userinfo.fname + ", your user ID is " + userinfo.userid + ". Boom!"); });
  • 31. questions? (thanks!) slides: http://www.slideshare.net/jeffreyzinn/wcla12-javascript code: https://gist.github.com/3718135