WordPress Development Tools and Best Practices

9,147 views

Published on

Published in: Technology
1 Comment
12 Likes
Statistics
Notes
No Downloads
Views
Total views
9,147
On SlideShare
0
From Embeds
0
Number of Embeds
1,636
Actions
Shares
0
Downloads
72
Comments
1
Likes
12
Embeds 0
No embeds

No notes for slide

WordPress Development Tools and Best Practices

  1. WordPress Development Tools and Best Practices di DANILO ERCOLI WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13sabato 9 febbraio 13
  2. AGENDA • The WordPress Codex • Coding Standards • wpshell and wp-cli • Deferred Execution: jobs system • Escape and Sanitize • Enqueue scripts and styles • Caching WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13sabato 9 febbraio 13
  3. WORDPRESS DEVELOPMENT TOOLS WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13sabato 9 febbraio 13
  4. THE WORDPRESS CODEX • The online manual for WordPress Developers • http://codex.wordpress.org • The Codex is a wiki, meaning anyone can edit it. It grows and thrives off of individual contributions from people like you • WordPress Coding Standards http://codex.wordpress.org/WordPress_Coding_Standards General information about coding standards for WordPress development WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13sabato 9 febbraio 13
  5. THE WORDPRESS CODEX • Writing a Plugin http://codex.wordpress.org/Writing_a_Plugin The best starting place for learning about how to develop plugins • Working with Themes https://codex.wordpress.org/Theme_Development Shows the technical aspects of writing code to build your own Themes • Data Validation http://codex.wordpress.org/Data_Validation A must-read for WordPress contributors. Describes the functions used by WordPress to validate and sanitize data. Developers should be familiar with these functions and ideas WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13sabato 9 febbraio 13
  6. WORDPRESS COMMAND LINE INTERFACE Currently, there is only one way of talking to a WordPress installation: HTTP requests. Whether you use a web browser, an XML-RPC application or just wget, it’s still just HTTP underneath. wp-cli allows you to control WordPress through the command-line. There are internal commands like option (manipulate options table values), user (create, edit, or delete users), or post (create, edit, or delete posts). # Get the value of a certain option wpcli option get my_option wpcli user list  --blog=mioblog.wordpress.com wpcli theme status --blog=mioblog.wordpress.com # Activate a newly installed theme on a particular site in a multisite setup wpcli theme activate my-new-theme --blog=fooblog.example.com WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13sabato 9 febbraio 13
  7. WORDPRESS COMMAND LINE INTERFACE wp-cli is far better than writing your own bin scripts for many reasons: • Promotes reusability over one-off or poorly architected scripts • The real value in this is automation and seamless integration with other tools: cron jobs, deployment scripts etc • Many built-in tools like WP_CLI::line() which ensure your code is simply the logic you need to execute • There already are several popular plugins that work with wp-cli. If you’re using WP Super-Cache, you can run the following command: wp super-cache flush https://github.com/wp-cli/wp-cli WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13sabato 9 febbraio 13
  8. WPSHELL • wpshell is a command line shell suitable for any php project, includes code indexing, searching, and displaying built-in • It gives you a command shell that accepts native PHP code as well as all the functionality your regular WordPress install would give you • http://code.trac.wordpress.org/ - http://hitchhackerguide.com/2011/11/13/ wpshell-a-shell-for-wordpress/ • This is intended for advanced developers. If you don’t know what you’re doing you can easily mess up your WordPress install. You can delete posts/ users/anything in few commands • I would not run this on production, but only in a local development environment. We will run it in production on WordPress.com (but rollback is easy there) • Examples! WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13sabato 9 febbraio 13
  9. DEBUG PLUGINS • Debug Bar http://wordpress.org/extend/plugins/debug-bar/ Adds a debug menu to the admin bar that shows query, cache, and other helpful debugging information. • Debug-Bar-Extender http://wordpress.org/extend/plugins/debug-bar-extender/ Extends the debug-bar plugin with additional tabs to measure runtimes between checkpoints and lookup variable content. (Do not use in a production site). • Debug Bar Console http://wordpress.org/extend/plugins/debug-bar-console/ Adds a PHP/MySQL console to the debug bar. Requires the debug bar plugin. WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13sabato 9 febbraio 13
  10. DEFERRED EXECUTION - JOBS SYSTEM PHP, as we all know, executes in a single threaded manner. That is the interpreter does A, then B, then C, then D, then finishes, and wipes its slate clean (shared nothing.) It does this same things for every page view on your site. For example, You have a social networking site that allows your users to send each other messages, the execution for that action might be something like this: • setup web environment • setup user environment • check user permissions • check message to make sure its not spam • check message to make sure its not a duplicate • check message for bad language • insert the message into the db for the recipient(s) • send out email to remote user(s) letting them know that they have a message waiting for them now • render the "message sent" page for the sender WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13sabato 9 febbraio 13
  11. DEFERRED EXECUTION - JOBS SYSTEM The jobs system changes everything. With the jobs system you can stash the message into a job after checking permissions, and skip straight to rendering the "message sent" page. Another process elsewhere on your network will pick up the job, pull out the message, check it for duplication, spam, language, stick it in the db if that all passes, and then finally send out emails to all the recipients. Examples, The Jobs System in Action! WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13sabato 9 febbraio 13
  12. DEFERRED EXECUTION - JOBS SYSTEM • A Web user interface to tell you what’s going on. • A distributed fault tolerant crontab replacement. • Statistics on your servers and your jobs. • Error logs -- any output of a failed job (including STDERR output) is recorded along with the job in the db accessible from the UI. • Scaleability -- setup multiple jobs clusters or add new servers to the existing one. Adding new servers happens automatically, just works. Different servers can be told how many simultaneous workers theyre allowed right from the web UI • Integration -- As a PHP application its meant to, literally, include your whole code base allowing your environment to be accessible with no differences at all to developers • http://code.trac.wordpress.org/ WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13sabato 9 febbraio 13
  13. DEFERRED EXECUTION - JOBS SYSTEM WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13sabato 9 febbraio 13
  14. CACHING WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13sabato 9 febbraio 13
  15. DIFFERENT TYPES OF CACHING Full page caching •WP Super Cache •Batcache •W3 Total Cache Object level caching with native caching APIs •W3 Total Cache •WP File Cache •APC •Memcached Object Cache WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13sabato 9 febbraio 13
  16. FULL PAGE CACHE: BATCACHE What is Batcache? Batcache is a plugin to store and serve cached versions of rendered pages. • Batcache uses memcached as its storage and is aimed at preventing a flood of traffic from breaking your site. It does this by serving old pages to new users. • This reduces the demand on the web server CPU and the database. It also means some people may see a page that is up to 5 minutes old. • Development testing showed a 40x reduction in page generation times: pages generated in 200ms were served from the cache in 5ms. • Traffic simulations with Siege demonstrate that WordPress can handle up to twenty times more traffic with Batcache installed. WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13sabato 9 febbraio 13
  17. PAGE CACHE: BATCACHE Who receives a cached pageview? • By default, all new users receive a cached pageview. • New users are defined as anybody who hasn’t interacted with your domain — once they’ve left a comment or logged in, their cookies will ensure they get fresh pages. • Note that URLs with query strings are automatically exempt from Batcache. $batcache[max_age] = 300; // Expire batcache items aged this many seconds (zero to disable it) $batcache[times] = 4; // Only batcache a page after it is accessed this many times. WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13sabato 9 febbraio 13
  18. PAGE CACHE: BATCACHE Because Batcache caches fully rendered pages, per-user interactions on the server-side can be problematic. This means usage of objects/functions like $_COOKIE, setcookie, $_SERVER[HTTP_USER_AGENT], and anything that’s unique to an individual user cannot be relied on as the values may be cached and cross- pollution can occur. In most cases, any user-level interactions should be moved to client-side using JavaScript. In some cases, we can help you set up Batcache variants if you’re limiting your interactions to a small set of distinct groups. (e.g. serve different content for users depending on whether the cookie “customer-type” is set, or equals “paid” or “pending”). Please get in touch if this something you’re interested in setting up. WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13sabato 9 febbraio 13
  19. PAGE CACHE: BATCACHE Batcache Variants if ( Jetpack_User_Agent_Info::is_blackbeberry() ) { " $batcache[unique][mobile] = blackberry; } elseif ( Jetpack_User_Agent_Info::is_WindowsPhone7() ) { " " $batcache[unique][mobile] = windows-phone7;" } elseif ( Jetpack_User_Agent_Info::is_S60_OSSBrowser() ) { " $batcache[unique][mobile] = dumb; } elseif ( in_array( jetpack_is_mobile( smart, true ), array( iphone ) ) ) { " $batcache[unique][mobile] = iphone; } elseif ( jetpack_is_mobile( dumb ) ) { " $batcache[unique][mobile] = dumb; } WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13sabato 9 febbraio 13
  20. WORDPRESS NATIVE CACHING APIS Transients • Persistent out of the box • Stored in wp_options: _transient_{key} • WordPress uses for certain internal functions • set_, get_, and delete_transient() Object Cache • Not persistent without a plugin, such as W3 Total Cache or Memcached Object Cache • Storage depends on servers and plugins capabilities • Used extensively within WordPress Cache objects can be grouped wp_cache_add(), _set, _get, _delete WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13sabato 9 febbraio 13
  21. BEST PRACTICES WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13sabato 9 febbraio 13
  22. CODINGS STANDARDS (1) • Single quotes unless you need to evaluate a variable <?php echo a great string; ?> vs <?php $dog_name = Winston; echo "my dogs name is: $dog_name"; ?> • Naming is important $myGreatVariable = 2; //not so much $my_great_variable = my_function(); //Correct WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13sabato 9 febbraio 13
  23. CODINGS STANDARDS (2) • Yoda conditions if ( $city == Montreal ) vs. if ( Montreal == $city ) • Don’t get too clever isset( $var ) || $var = some_function(); Easier to read: if ( ! isset( $var ) ) $var = some_function(); WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13sabato 9 febbraio 13
  24. PROPERLY VALIDATE, SANITIZE, AND ESCAPE YOUR DATA Your code works, but is it safe? Rule No. 1: Trust Nobody The idea is that you should not assume that any data entered by the user is safe. Nor should you assume that the data you’ve retrieved from the database is safe – even if you had made it ‘safe’ prior to inserting it there. •In fact, whether data can be considered ‘safe’ makes no sense without context. •Sometimes the same data may be used in multiple contexts on the same page. Rule No. 2: Validate on Input, Escape on Output To escape is to take the data you may already have and help secure it prior to rendering it for the end user WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13sabato 9 febbraio 13
  25. VALIDATING: CHECKING USER INPUT To validate is to ensure the data you’ve requested of the user matches what they’ve submitted. There are several core methods you can use for input validation; usage obviously depends on the type of fields you’d like to validate. http://codex.wordpress.org/Data_Validation#Input_Validation Let’s take a look at an example. <input id="my-zipcode" type="text" maxlength="5" name="my-zipcode" /> We’ve limited the input to five characters of input, but there’s no limitation on what they can input. They could enter “11221″ or “eval(“. Or even more characters if they change the HTML. WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13sabato 9 febbraio 13
  26. VALIDATING: CHECKING USER INPUT 1  $safe_zipcode  =  intval(  $_POST[my-­‐zipcode]  ); 2  if  (  !  $safe_zipcode  ) 3      $safe_zipcode  =  ; 4  update_post_meta(  $post-­‐>ID,  my_zipcode,  $safe_zipcode  ); The intval() function casts user input as an integer, and defaults to zero if the input was a non-numeric value. We then check to see if the value ended up as zero. If it did, we’ll save an empty value to the database. Otherwise, we’ll save the properly validated zipcode. WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13sabato 9 febbraio 13
  27. SANITIZING: CLEANING USER INPUT Whereas validation is concerned with making sure data is valid – data sanitization is about making it safe. Even ‘valid’ data might be unsafe in certain contexts. You cannot ask “How do I make this data safe?”. Instead you should ask, “How do I make this data safe for using it in X”. <input  id="title"  type="text"  name="title"  /> We could sanitize the data with the sanitize_text_field() function: Tex$title  =  sanitize_text_field(  $_POST[title]  ); 2 update_post_meta(  $post-­‐>ID,  title,  $title  ); t WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13sabato 9 febbraio 13
  28. SANITIZING: CLEANING USER INPUT Behinds the scenes, the function does the following: • Checks for invalid UTF-8 • Converts single < characters to entity • Strips all tags • Remove line breaks, tabs and extra white space • Strip octets The sanitize_*() class of helper functions are super nice for us, as they ensure we’re ending up with safe data and require minimal effort on our part. WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13sabato 9 febbraio 13
  29. ESCAPING: SECURING OUTPUT For security on the other end of the spectrum, we have escaping. To escape is to take the data you may already have and help secure it prior to rendering it for the end user. WordPress thankfully has a few helper functions we can use for most of what we’ll commonly need to do: esc_html() we should use anytime our HTML element encloses a section of data we’re outputting. </pre> <h4><!-­‐-­‐?php  echo  esc_html(  $title  );  ?-­‐-­‐></h4> <pre> esc_url() should be used on all URLs, including those in the ‘src’ and ‘href’ attributes of an HTML element. <img  alt=""  src="<?php  echo  esc_url(  $great_user_picture_url  );  ?>"  /> WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13sabato 9 febbraio 13
  30. ESCAPING: SECURING OUTPUT esc_js() is intended for inline JavaScript. var  value  =  <?php  echo  esc_js(  $value  );  ?>; esc_attr() can be used on everything else that’s printed into an HTML element’s attribute. <ul  class="<?php  echo  esc_attr(  $stored_class  );  ?>"> It’s important to note that most WordPress functions properly prepare the data for output, and you don’t need to escape again. <h4><?php  the_title();  ?></h4> WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13sabato 9 febbraio 13
  31. JAVASCRIPT & CSS • Use wp_register_script() and wp_enqueue_script() to initialize your JavaScript files. This ensures compatibility with other plugins and avoids conflicts. • The jQuery version that is packaged with WordPress is in compatibility mode. This means that jQuery() needs to be explicitly used, not the $() short form. • If you need to register a script that is not part of WordPress, or your theme, make sure to use a packed version if available and make sure that their servers are up for the traffic you will request from them. Fail gracefully. • Use wp_enqueue_style() to load stylesheets • Make sure to use relative paths for URLs in your stylesheet. • Avoid generating style definitions with PHP, as having a static CSS file delivered from CDNs is much faster than generating a style via a PHP script. WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13sabato 9 febbraio 13
  32. RELATORE Danilo Ercoli Web: http://daniloercoli.wordpress.com Twitter: @daniloercoli BIO Danilo ha più di 10 anni di esperienza nello sviluppo di soluzioni software per il web e per il mobile. Ha lavorato con i più disparati linguaggi di programmazione, dall’assembler a SmallTalk, dal C all’ Object-C passando per Lisp, Java e PHP. Sviluppatore certificato PHP e Java2 SE. Molto tempo fa ha anche scritto un compilatore per il linguaggio Tiger. Attualmente lavora in WordPress.com passando gran parte del tempo sviluppando le soluzioni mobili offerte da WordPress e sviluppando componenti server a supporto del mobile. Lead Developer di WordPress for BlackBerry and PlayBook. WORDCAMP BOLOGNA - 9 FEBBRAIO 2013 @WORDCAMPBOLOGNA # WPCAMPBO13sabato 9 febbraio 13

×