SlideShare a Scribd company logo
1 of 31
Download to read offline
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

Introduction to Vue.js
Introduction to Vue.jsIntroduction to Vue.js
Introduction to Vue.jsMeir Rotstein
 
Enjoy the vue.js
Enjoy the vue.jsEnjoy the vue.js
Enjoy the vue.jsTechExeter
 
Difference between java script and jquery
Difference between java script and jqueryDifference between java script and jquery
Difference between java script and jqueryUmar Ali
 
Introduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress DevelopersIntroduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress DevelopersCaldera Labs
 
How to Build SPA with Vue Router 2.0
How to Build SPA with Vue Router 2.0How to Build SPA with Vue Router 2.0
How to Build SPA with Vue Router 2.0Takuya Tejima
 
Making Magento flying like a rocket! (A set of valuable tips for developers)
Making Magento flying like a rocket! (A set of valuable tips for developers)Making Magento flying like a rocket! (A set of valuable tips for developers)
Making Magento flying like a rocket! (A set of valuable tips for developers)Ivan Chepurnyi
 
20130528 solution linux_frousseau_nopain_webdev
20130528 solution linux_frousseau_nopain_webdev20130528 solution linux_frousseau_nopain_webdev
20130528 solution linux_frousseau_nopain_webdevFrank Rousseau
 
Better Testing With PHP Unit
Better Testing With PHP UnitBetter Testing With PHP Unit
Better Testing With PHP Unitsitecrafting
 
Creating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of todayCreating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of todaygerbille
 
Building a Startup Stack with AngularJS
Building a Startup Stack with AngularJSBuilding a Startup Stack with AngularJS
Building a Startup Stack with AngularJSFITC
 
#NewMeetup Performance
#NewMeetup Performance#NewMeetup Performance
#NewMeetup PerformanceJustin Cataldo
 
Meetup Performance
Meetup PerformanceMeetup Performance
Meetup PerformanceGreg Whalin
 
2012.sandiego.wordcamp
2012.sandiego.wordcamp2012.sandiego.wordcamp
2012.sandiego.wordcampBrandon Dove
 
Effective C++/WinRT for UWP and Win32
Effective C++/WinRT for UWP and Win32Effective C++/WinRT for UWP and Win32
Effective C++/WinRT for UWP and Win32Windows Developer
 
EWD 3 Training Course Part 38: Building a React.js application with QEWD, Part 4
EWD 3 Training Course Part 38: Building a React.js application with QEWD, Part 4EWD 3 Training Course Part 38: Building a React.js application with QEWD, Part 4
EWD 3 Training Course Part 38: Building a React.js application with QEWD, Part 4Rob Tweed
 
Introduction to Backbone.js & Marionette.js
Introduction to Backbone.js & Marionette.jsIntroduction to Backbone.js & Marionette.js
Introduction to Backbone.js & Marionette.jsReturn on Intelligence
 
IndexedDB - Querying and Performance
IndexedDB - Querying and PerformanceIndexedDB - Querying and Performance
IndexedDB - Querying and PerformanceParashuram N
 

What's hot (20)

Introduction to Vue.js
Introduction to Vue.jsIntroduction to Vue.js
Introduction to Vue.js
 
Enjoy the vue.js
Enjoy the vue.jsEnjoy the vue.js
Enjoy the vue.js
 
Difference between java script and jquery
Difference between java script and jqueryDifference between java script and jquery
Difference between java script and jquery
 
Symfony2 and AngularJS
Symfony2 and AngularJSSymfony2 and AngularJS
Symfony2 and AngularJS
 
Sane Async Patterns
Sane Async PatternsSane Async Patterns
Sane Async Patterns
 
Introduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress DevelopersIntroduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress Developers
 
How to Build SPA with Vue Router 2.0
How to Build SPA with Vue Router 2.0How to Build SPA with Vue Router 2.0
How to Build SPA with Vue Router 2.0
 
Making Magento flying like a rocket! (A set of valuable tips for developers)
Making Magento flying like a rocket! (A set of valuable tips for developers)Making Magento flying like a rocket! (A set of valuable tips for developers)
Making Magento flying like a rocket! (A set of valuable tips for developers)
 
20130528 solution linux_frousseau_nopain_webdev
20130528 solution linux_frousseau_nopain_webdev20130528 solution linux_frousseau_nopain_webdev
20130528 solution linux_frousseau_nopain_webdev
 
Better Testing With PHP Unit
Better Testing With PHP UnitBetter Testing With PHP Unit
Better Testing With PHP Unit
 
Creating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of todayCreating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of today
 
Ajax Security
Ajax SecurityAjax Security
Ajax Security
 
Building a Startup Stack with AngularJS
Building a Startup Stack with AngularJSBuilding a Startup Stack with AngularJS
Building a Startup Stack with AngularJS
 
#NewMeetup Performance
#NewMeetup Performance#NewMeetup Performance
#NewMeetup Performance
 
Meetup Performance
Meetup PerformanceMeetup Performance
Meetup Performance
 
2012.sandiego.wordcamp
2012.sandiego.wordcamp2012.sandiego.wordcamp
2012.sandiego.wordcamp
 
Effective C++/WinRT for UWP and Win32
Effective C++/WinRT for UWP and Win32Effective C++/WinRT for UWP and Win32
Effective C++/WinRT for UWP and Win32
 
EWD 3 Training Course Part 38: Building a React.js application with QEWD, Part 4
EWD 3 Training Course Part 38: Building a React.js application with QEWD, Part 4EWD 3 Training Course Part 38: Building a React.js application with QEWD, Part 4
EWD 3 Training Course Part 38: Building a React.js application with QEWD, Part 4
 
Introduction to Backbone.js & Marionette.js
Introduction to Backbone.js & Marionette.jsIntroduction to Backbone.js & Marionette.js
Introduction to Backbone.js & Marionette.js
 
IndexedDB - Querying and Performance
IndexedDB - Querying and PerformanceIndexedDB - Querying and Performance
IndexedDB - Querying and Performance
 

Viewers also liked

Ashby regolamento ing_web
Ashby regolamento ing_webAshby regolamento ing_web
Ashby regolamento ing_webJames LaFleur
 
Guia de calculo periodo 1
Guia de calculo periodo 1Guia de calculo periodo 1
Guia de calculo periodo 1Jack Toloza
 
The earth
The earthThe earth
The earthsvpp11
 
Escape from Excel - Retail Can't Survive and Thrive on Spreadsheets
Escape from Excel - Retail Can't Survive and Thrive on SpreadsheetsEscape from Excel - Retail Can't Survive and Thrive on Spreadsheets
Escape from Excel - Retail Can't Survive and Thrive on SpreadsheetsJerry Inman
 
מהו צדק עברית2
מהו צדק עברית2מהו צדק עברית2
מהו צדק עברית2taliaramati
 
Studio67 ref model
Studio67 ref modelStudio67 ref model
Studio67 ref modelm2nd7
 
το βιβλίο και ο υπολογιστής
το βιβλίο και ο υπολογιστήςτο βιβλίο και ο υπολογιστής
το βιβλίο και ο υπολογιστήςEleni Papadopoulou
 
выбираем будущую профессию
выбираем будущую профессиювыбираем будущую профессию
выбираем будущую профессиюmaychik1995
 
Input Output Devices (An Introduction)
Input Output Devices (An Introduction)Input Output Devices (An Introduction)
Input Output Devices (An Introduction)Qsrealm
 

Viewers also liked (20)

Ashby regolamento ing_web
Ashby regolamento ing_webAshby regolamento ing_web
Ashby regolamento ing_web
 
Беларусы ў Пецярбургу
Беларусы ў ПецярбургуБеларусы ў Пецярбургу
Беларусы ў Пецярбургу
 
Guia de calculo periodo 1
Guia de calculo periodo 1Guia de calculo periodo 1
Guia de calculo periodo 1
 
Christmas11 12
Christmas11 12Christmas11 12
Christmas11 12
 
Письмо с. 21
Письмо с. 21Письмо с. 21
Письмо с. 21
 
The earth
The earthThe earth
The earth
 
Pertemuan 4
Pertemuan 4Pertemuan 4
Pertemuan 4
 
Письмо с. 22
Письмо с. 22Письмо с. 22
Письмо с. 22
 
Письмо элементов
Письмо элементовПисьмо элементов
Письмо элементов
 
Rodohori
RodohoriRodohori
Rodohori
 
Presentasi psi
Presentasi psiPresentasi psi
Presentasi psi
 
Escape from Excel - Retail Can't Survive and Thrive on Spreadsheets
Escape from Excel - Retail Can't Survive and Thrive on SpreadsheetsEscape from Excel - Retail Can't Survive and Thrive on Spreadsheets
Escape from Excel - Retail Can't Survive and Thrive on Spreadsheets
 
Programma filologou
Programma filologouProgramma filologou
Programma filologou
 
Jayanta Hazarika
Jayanta HazarikaJayanta Hazarika
Jayanta Hazarika
 
מהו צדק עברית2
מהו צדק עברית2מהו צדק עברית2
מהו צדק עברית2
 
Studio67 ref model
Studio67 ref modelStudio67 ref model
Studio67 ref model
 
το βιβλίο και ο υπολογιστής
το βιβλίο και ο υπολογιστήςτο βιβλίο και ο υπολογιστής
το βιβλίο και ο υπολογιστής
 
Ucronia
UcroniaUcronia
Ucronia
 
выбираем будущую профессию
выбираем будущую профессиювыбираем будущую профессию
выбираем будущую профессию
 
Input Output Devices (An Introduction)
Input Output Devices (An Introduction)Input Output Devices (An Introduction)
Input Output Devices (An Introduction)
 

Similar to WCLA12 JavaScript

[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress Development[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress DevelopmentAdam Tomat
 
Flash Widget Tutorial
Flash Widget TutorialFlash Widget Tutorial
Flash Widget Tutorialhussulinux
 
JavaScript & AJAX in WordPress
JavaScript & AJAX in WordPressJavaScript & AJAX in WordPress
JavaScript & AJAX in WordPressIgor Benić
 
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
 
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
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkBo-Yi Wu
 
Как получить чёрный пояс по WordPress?
Как получить чёрный пояс по WordPress?Как получить чёрный пояс по WordPress?
Как получить чёрный пояс по WordPress?Yevhen Kotelnytskyi
 
Becoming a better WordPress Developer
Becoming a better WordPress DeveloperBecoming a better WordPress Developer
Becoming a better WordPress DeveloperJoey Kudish
 
"Your script just killed my site" by Steve Souders
"Your script just killed my site" by Steve Souders"Your script just killed my site" by Steve Souders
"Your script just killed my site" by Steve SoudersDmitry Makarchuk
 
WordPress Theme Design and Development Workshop - Day 3
WordPress Theme Design and Development Workshop - Day 3WordPress Theme Design and Development Workshop - Day 3
WordPress Theme Design and Development Workshop - Day 3Mizanur Rahaman Mizan
 
Real World Dependency Injection - phpday
Real World Dependency Injection - phpdayReal World Dependency Injection - phpday
Real World Dependency Injection - phpdayStephan Hochdörfer
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)Igor Bronovskyy
 
Wordpress plugin development tips
Wordpress plugin development tipsWordpress plugin development tips
Wordpress plugin development tipsMindfire Solutions
 
WordPress Plugin development
WordPress Plugin developmentWordPress Plugin development
WordPress Plugin developmentMostafa Soufi
 
Offline Application Cache
Offline Application CacheOffline Application Cache
Offline Application CacheJonathan Stark
 

Similar to WCLA12 JavaScript (20)

WCLV13 JavaScript
WCLV13 JavaScriptWCLV13 JavaScript
WCLV13 JavaScript
 
Yii Introduction
Yii IntroductionYii Introduction
Yii Introduction
 
[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress Development[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress Development
 
Flash Widget Tutorial
Flash Widget TutorialFlash Widget Tutorial
Flash Widget Tutorial
 
Rails is not just Ruby
Rails is not just RubyRails is not just Ruby
Rails is not just Ruby
 
JavaScript & AJAX in WordPress
JavaScript & AJAX in WordPressJavaScript & AJAX in WordPress
JavaScript & AJAX in WordPress
 
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
 
WordPress and Ajax
WordPress and AjaxWordPress and Ajax
WordPress and Ajax
 
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 ...
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
 
Как получить чёрный пояс по WordPress?
Как получить чёрный пояс по WordPress?Как получить чёрный пояс по WordPress?
Как получить чёрный пояс по WordPress?
 
Becoming a better WordPress Developer
Becoming a better WordPress DeveloperBecoming a better WordPress Developer
Becoming a better WordPress Developer
 
"Your script just killed my site" by Steve Souders
"Your script just killed my site" by Steve Souders"Your script just killed my site" by Steve Souders
"Your script just killed my site" by Steve Souders
 
WordPress Theme Design and Development Workshop - Day 3
WordPress Theme Design and Development Workshop - Day 3WordPress Theme Design and Development Workshop - Day 3
WordPress Theme Design and Development Workshop - Day 3
 
Real World Dependency Injection - phpday
Real World Dependency Injection - phpdayReal World Dependency Injection - phpday
Real World Dependency Injection - phpday
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
 
Wordpress plugin development tips
Wordpress plugin development tipsWordpress plugin development tips
Wordpress plugin development tips
 
WordPress Plugin development
WordPress Plugin developmentWordPress Plugin development
WordPress Plugin development
 
Offline Application Cache
Offline Application CacheOffline Application Cache
Offline Application Cache
 
Sanjeev ghai 12
Sanjeev ghai 12Sanjeev ghai 12
Sanjeev ghai 12
 

Recently uploaded

办理国外毕业证学位证《原版美国montana文凭》蒙大拿州立大学毕业证制作成绩单修改
办理国外毕业证学位证《原版美国montana文凭》蒙大拿州立大学毕业证制作成绩单修改办理国外毕业证学位证《原版美国montana文凭》蒙大拿州立大学毕业证制作成绩单修改
办理国外毕业证学位证《原版美国montana文凭》蒙大拿州立大学毕业证制作成绩单修改atducpo
 
Call Girls in Kalyan Vihar Delhi 💯 Call Us 🔝8264348440🔝
Call Girls in Kalyan Vihar Delhi 💯 Call Us 🔝8264348440🔝Call Girls in Kalyan Vihar Delhi 💯 Call Us 🔝8264348440🔝
Call Girls in Kalyan Vihar Delhi 💯 Call Us 🔝8264348440🔝soniya singh
 
Postal Ballot procedure for employees to utilise
Postal Ballot procedure for employees to utilisePostal Ballot procedure for employees to utilise
Postal Ballot procedure for employees to utiliseccsubcollector
 
《塔夫斯大学毕业证成绩单购买》做Tufts文凭毕业证成绩单/伪造美国假文凭假毕业证书图片Q微信741003700《塔夫斯大学毕业证购买》《Tufts毕业文...
《塔夫斯大学毕业证成绩单购买》做Tufts文凭毕业证成绩单/伪造美国假文凭假毕业证书图片Q微信741003700《塔夫斯大学毕业证购买》《Tufts毕业文...《塔夫斯大学毕业证成绩单购买》做Tufts文凭毕业证成绩单/伪造美国假文凭假毕业证书图片Q微信741003700《塔夫斯大学毕业证购买》《Tufts毕业文...
《塔夫斯大学毕业证成绩单购买》做Tufts文凭毕业证成绩单/伪造美国假文凭假毕业证书图片Q微信741003700《塔夫斯大学毕业证购买》《Tufts毕业文...ur8mqw8e
 
办理西悉尼大学毕业证成绩单、制作假文凭
办理西悉尼大学毕业证成绩单、制作假文凭办理西悉尼大学毕业证成绩单、制作假文凭
办理西悉尼大学毕业证成绩单、制作假文凭o8wvnojp
 
The Selfspace Journal Preview by Mindbrush
The Selfspace Journal Preview by MindbrushThe Selfspace Journal Preview by Mindbrush
The Selfspace Journal Preview by MindbrushShivain97
 
Understanding Relationship Anarchy: A Guide to Liberating Love | CIO Women Ma...
Understanding Relationship Anarchy: A Guide to Liberating Love | CIO Women Ma...Understanding Relationship Anarchy: A Guide to Liberating Love | CIO Women Ma...
Understanding Relationship Anarchy: A Guide to Liberating Love | CIO Women Ma...CIOWomenMagazine
 
CALL ON ➥8923113531 🔝Call Girls Aliganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Aliganj Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Aliganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Aliganj Lucknow best sexual serviceanilsa9823
 
8377087607 Full Enjoy @24/7-CLEAN-Call Girls In Chhatarpur,
8377087607 Full Enjoy @24/7-CLEAN-Call Girls In Chhatarpur,8377087607 Full Enjoy @24/7-CLEAN-Call Girls In Chhatarpur,
8377087607 Full Enjoy @24/7-CLEAN-Call Girls In Chhatarpur,dollysharma2066
 
Lilac Illustrated Social Psychology Presentation.pptx
Lilac Illustrated Social Psychology Presentation.pptxLilac Illustrated Social Psychology Presentation.pptx
Lilac Illustrated Social Psychology Presentation.pptxABMWeaklings
 
Reinventing Corporate Philanthropy_ Strategies for Meaningful Impact by Leko ...
Reinventing Corporate Philanthropy_ Strategies for Meaningful Impact by Leko ...Reinventing Corporate Philanthropy_ Strategies for Meaningful Impact by Leko ...
Reinventing Corporate Philanthropy_ Strategies for Meaningful Impact by Leko ...Leko Durda
 
Call Girls In Andheri East Call US Pooja📞 9892124323 Book Hot And
Call Girls In Andheri East Call US Pooja📞 9892124323 Book Hot AndCall Girls In Andheri East Call US Pooja📞 9892124323 Book Hot And
Call Girls In Andheri East Call US Pooja📞 9892124323 Book Hot AndPooja Nehwal
 
Breath, Brain & Beyond_A Holistic Approach to Peak Performance.pdf
Breath, Brain & Beyond_A Holistic Approach to Peak Performance.pdfBreath, Brain & Beyond_A Holistic Approach to Peak Performance.pdf
Breath, Brain & Beyond_A Holistic Approach to Peak Performance.pdfJess Walker
 
Dhule Call Girls #9907093804 Contact Number Escorts Service Dhule
Dhule Call Girls #9907093804 Contact Number Escorts Service DhuleDhule Call Girls #9907093804 Contact Number Escorts Service Dhule
Dhule Call Girls #9907093804 Contact Number Escorts Service Dhulesrsj9000
 
(No.1)↠Young Call Girls in Sikanderpur (Gurgaon) ꧁❤ 9711911712 ❤꧂ Escorts
(No.1)↠Young Call Girls in Sikanderpur (Gurgaon) ꧁❤ 9711911712 ❤꧂ Escorts(No.1)↠Young Call Girls in Sikanderpur (Gurgaon) ꧁❤ 9711911712 ❤꧂ Escorts
(No.1)↠Young Call Girls in Sikanderpur (Gurgaon) ꧁❤ 9711911712 ❤꧂ EscortsDelhi Escorts Service
 
Call Girls in Govindpuri Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Govindpuri Delhi 💯Call Us 🔝8264348440🔝Call Girls in Govindpuri Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Govindpuri Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Lucknow 💋 High Class Call Girls Lucknow 10k @ I'm VIP Independent Escorts Gir...
Lucknow 💋 High Class Call Girls Lucknow 10k @ I'm VIP Independent Escorts Gir...Lucknow 💋 High Class Call Girls Lucknow 10k @ I'm VIP Independent Escorts Gir...
Lucknow 💋 High Class Call Girls Lucknow 10k @ I'm VIP Independent Escorts Gir...anilsa9823
 
REFLECTIONS Newsletter Jan-Jul 2024.pdf.pdf
REFLECTIONS Newsletter Jan-Jul 2024.pdf.pdfREFLECTIONS Newsletter Jan-Jul 2024.pdf.pdf
REFLECTIONS Newsletter Jan-Jul 2024.pdf.pdfssusere8ea60
 
call girls in candolim beach 9870370636] NORTH GOA ..
call girls in candolim beach 9870370636] NORTH GOA ..call girls in candolim beach 9870370636] NORTH GOA ..
call girls in candolim beach 9870370636] NORTH GOA ..nishakur201
 

Recently uploaded (20)

办理国外毕业证学位证《原版美国montana文凭》蒙大拿州立大学毕业证制作成绩单修改
办理国外毕业证学位证《原版美国montana文凭》蒙大拿州立大学毕业证制作成绩单修改办理国外毕业证学位证《原版美国montana文凭》蒙大拿州立大学毕业证制作成绩单修改
办理国外毕业证学位证《原版美国montana文凭》蒙大拿州立大学毕业证制作成绩单修改
 
Call Girls in Kalyan Vihar Delhi 💯 Call Us 🔝8264348440🔝
Call Girls in Kalyan Vihar Delhi 💯 Call Us 🔝8264348440🔝Call Girls in Kalyan Vihar Delhi 💯 Call Us 🔝8264348440🔝
Call Girls in Kalyan Vihar Delhi 💯 Call Us 🔝8264348440🔝
 
Postal Ballot procedure for employees to utilise
Postal Ballot procedure for employees to utilisePostal Ballot procedure for employees to utilise
Postal Ballot procedure for employees to utilise
 
《塔夫斯大学毕业证成绩单购买》做Tufts文凭毕业证成绩单/伪造美国假文凭假毕业证书图片Q微信741003700《塔夫斯大学毕业证购买》《Tufts毕业文...
《塔夫斯大学毕业证成绩单购买》做Tufts文凭毕业证成绩单/伪造美国假文凭假毕业证书图片Q微信741003700《塔夫斯大学毕业证购买》《Tufts毕业文...《塔夫斯大学毕业证成绩单购买》做Tufts文凭毕业证成绩单/伪造美国假文凭假毕业证书图片Q微信741003700《塔夫斯大学毕业证购买》《Tufts毕业文...
《塔夫斯大学毕业证成绩单购买》做Tufts文凭毕业证成绩单/伪造美国假文凭假毕业证书图片Q微信741003700《塔夫斯大学毕业证购买》《Tufts毕业文...
 
办理西悉尼大学毕业证成绩单、制作假文凭
办理西悉尼大学毕业证成绩单、制作假文凭办理西悉尼大学毕业证成绩单、制作假文凭
办理西悉尼大学毕业证成绩单、制作假文凭
 
The Selfspace Journal Preview by Mindbrush
The Selfspace Journal Preview by MindbrushThe Selfspace Journal Preview by Mindbrush
The Selfspace Journal Preview by Mindbrush
 
Understanding Relationship Anarchy: A Guide to Liberating Love | CIO Women Ma...
Understanding Relationship Anarchy: A Guide to Liberating Love | CIO Women Ma...Understanding Relationship Anarchy: A Guide to Liberating Love | CIO Women Ma...
Understanding Relationship Anarchy: A Guide to Liberating Love | CIO Women Ma...
 
CALL ON ➥8923113531 🔝Call Girls Aliganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Aliganj Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Aliganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Aliganj Lucknow best sexual service
 
8377087607 Full Enjoy @24/7-CLEAN-Call Girls In Chhatarpur,
8377087607 Full Enjoy @24/7-CLEAN-Call Girls In Chhatarpur,8377087607 Full Enjoy @24/7-CLEAN-Call Girls In Chhatarpur,
8377087607 Full Enjoy @24/7-CLEAN-Call Girls In Chhatarpur,
 
Lilac Illustrated Social Psychology Presentation.pptx
Lilac Illustrated Social Psychology Presentation.pptxLilac Illustrated Social Psychology Presentation.pptx
Lilac Illustrated Social Psychology Presentation.pptx
 
Reinventing Corporate Philanthropy_ Strategies for Meaningful Impact by Leko ...
Reinventing Corporate Philanthropy_ Strategies for Meaningful Impact by Leko ...Reinventing Corporate Philanthropy_ Strategies for Meaningful Impact by Leko ...
Reinventing Corporate Philanthropy_ Strategies for Meaningful Impact by Leko ...
 
Call Girls In Andheri East Call US Pooja📞 9892124323 Book Hot And
Call Girls In Andheri East Call US Pooja📞 9892124323 Book Hot AndCall Girls In Andheri East Call US Pooja📞 9892124323 Book Hot And
Call Girls In Andheri East Call US Pooja📞 9892124323 Book Hot And
 
Breath, Brain & Beyond_A Holistic Approach to Peak Performance.pdf
Breath, Brain & Beyond_A Holistic Approach to Peak Performance.pdfBreath, Brain & Beyond_A Holistic Approach to Peak Performance.pdf
Breath, Brain & Beyond_A Holistic Approach to Peak Performance.pdf
 
Dhule Call Girls #9907093804 Contact Number Escorts Service Dhule
Dhule Call Girls #9907093804 Contact Number Escorts Service DhuleDhule Call Girls #9907093804 Contact Number Escorts Service Dhule
Dhule Call Girls #9907093804 Contact Number Escorts Service Dhule
 
(No.1)↠Young Call Girls in Sikanderpur (Gurgaon) ꧁❤ 9711911712 ❤꧂ Escorts
(No.1)↠Young Call Girls in Sikanderpur (Gurgaon) ꧁❤ 9711911712 ❤꧂ Escorts(No.1)↠Young Call Girls in Sikanderpur (Gurgaon) ꧁❤ 9711911712 ❤꧂ Escorts
(No.1)↠Young Call Girls in Sikanderpur (Gurgaon) ꧁❤ 9711911712 ❤꧂ Escorts
 
Call Girls in Govindpuri Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Govindpuri Delhi 💯Call Us 🔝8264348440🔝Call Girls in Govindpuri Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Govindpuri Delhi 💯Call Us 🔝8264348440🔝
 
escort service sasti (*~Call Girls in Paschim Vihar Metro❤️9953056974
escort service  sasti (*~Call Girls in Paschim Vihar Metro❤️9953056974escort service  sasti (*~Call Girls in Paschim Vihar Metro❤️9953056974
escort service sasti (*~Call Girls in Paschim Vihar Metro❤️9953056974
 
Lucknow 💋 High Class Call Girls Lucknow 10k @ I'm VIP Independent Escorts Gir...
Lucknow 💋 High Class Call Girls Lucknow 10k @ I'm VIP Independent Escorts Gir...Lucknow 💋 High Class Call Girls Lucknow 10k @ I'm VIP Independent Escorts Gir...
Lucknow 💋 High Class Call Girls Lucknow 10k @ I'm VIP Independent Escorts Gir...
 
REFLECTIONS Newsletter Jan-Jul 2024.pdf.pdf
REFLECTIONS Newsletter Jan-Jul 2024.pdf.pdfREFLECTIONS Newsletter Jan-Jul 2024.pdf.pdf
REFLECTIONS Newsletter Jan-Jul 2024.pdf.pdf
 
call girls in candolim beach 9870370636] NORTH GOA ..
call girls in candolim beach 9870370636] NORTH GOA ..call girls in candolim beach 9870370636] NORTH GOA ..
call girls in candolim beach 9870370636] NORTH GOA ..
 

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