Cover image for Building Web Apps with WordPress

Book description

WordPress is much more than a blogging platform. As this practical guide clearly demonstrates, you can use WordPress to build web apps of any type—not mere content sites, but full-blown apps for specific tasks. If you have PHP experience with a smattering of HTML, CSS, and JavaScript, you’ll learn how to use WordPress plugins and themes to develop fast, scalable, and secure web apps, native mobile apps, web services, and even a network of multiple WordPress sites.

Table of Contents

  1. Preface
    1. Who This Book Is For
    2. Who This Book Is Not For
    3. What You’ll Learn
    4. About the Code
    5. Conventions Used in This Book
    6. Using Code Examples
    7. Safari® Books Online
    8. How to Contact Us
    9. Acknowledgments
  2. Foreword
  3. 1. Building Web Apps with WordPress
    1. What Is a Website?
    2. What Is an App?
    3. What Is a Web App?
      1. Features of a Web App
    4. Why Use WordPress?
      1. You Are Already Using WordPress
      2. Content Management Is Easy with WordPress
      3. User Management Is Easy and Secure with WordPress
      4. Plugins
      5. Flexibility Is Important
      6. Frequent Security Updates
      7. Cost
      8. .NET App
      9. WordPress App
      10. Responses to Some Common Criticisms of WordPress
    5. When Not to Use WordPress
      1. You Plan to License or Sell Your Site’s Technology
      2. There Is Another Platform That Will Get You “There” Faster
      3. Flexibility Is NOT Important to You
      4. Your App Needs to Be Highly Real Time
    6. WordPress as an Application Framework
      1. WordPress Versus MVC Frameworks
        1. MVC plugins for WordPress
        2. Models = plugins
        3. Views = themes
        4. Controllers = template loader
    7. Anatomy of a WordPress App
      1. What Is SchoolPress?
      2. SchoolPress Runs on a WordPress Multisite Network
      3. The SchoolPress Business Model
      4. Membership Levels and User Roles
      5. Classes Are BuddyPress Groups
      6. Assignments Are a Custom Post Type
      7. Submissions Are a (Sub)CPT for Assignments
      8. Semesters Are a Taxonomy on the Class CPT
      9. Departments Are a Taxonomy on the Class CPT
      10. SchoolPress Has One Main Custom Plugin
      11. SchoolPress Uses a Few Other Custom Plugins
      12. SchoolPress Uses the StartBox Theme Framework
  4. 2. WordPress Basics
    1. WordPress Directory Structure
      1. Root Directory
      2. /wp-admin
      3. /wp-includes
      4. /wp-content
        1. /wp-content/plugins
        2. /wp-content/themes
        3. /wp-content/uploads
        4. /wp-content/mu-plugins
    2. WordPress Database Structure
      1. wp_options
      2. Functions Found in /wp-includes/option.php
        1. add_option( $option, $value =
        2. update_option( $option, $newvalue )
        3. get_option( $option, $default = false )
        4. delete_option( $option )
      3. wp_users
      4. Functions Found in /wp-includes/…
        1. wp_insert_user( $userdata )
        2. wp_create_user( $username, $password, $email )
        3. wp_update_user( $userdata )
        4. get_user_by( $field, $value )
        5. get_userdata( $userid )
        6. wp_delete_user( $id, $reassign =
      5. wp_usermeta
        1. get_user_meta( $user_id, $key = '', $single = false )
        2. update_user_meta( $user_id, $meta_key, $meta_value, $prev_value = '' )
        3. add_user_meta($user_id, $meta_key, $meta_value, $unique = false)
        4. delete_user_meta($user_id, $meta_key, $meta_value = '')
      6. wp_posts
      7. Functions found in /wp-includes/post.php
        1. wp_insert_post($postarr, $wp_error = false)
        2. wp_update_post( $postarr = array(), $wp_error = false )
        3. get_post( $post = null, $output = OBJECT, $filter =
        4. get_posts($args = null)
        5. wp_delete_post( $postid = 0, $force_delete = false )
      8. wp_postmeta
      9. Functions Found in /wp-includes/post.php
        1. get_post_meta($post_id, $key = '', $single = false)
        2. update_post_meta($post_id, $meta_key, $meta_value, $prev_value = '')
        3. add_post_meta($post_id, $meta_key, $meta_value, $unique = false)
        4. delete_post_meta($post_id, $meta_key, $meta_value = '')
      10. wp_comments
      11. Functions Found in /wp-includes/comment.php
        1. get_comment( $comment, $output = OBJECT )
        2. get_comments( $args = '' )
        3. wp_insert_comment( $commentdata )
        4. wp_update_comment( $commentarr )
        5. wp_delete_comment( $comment_id, $force_delete = false )
      12. wp_commentsmeta
      13. Functions Found in /wp-includes/comment.php
        1. get_comment_meta($comment_id, $key = '', $single = false)
        2. add_comment_meta($comment_id, $meta_key, $meta_value, $unique = false)
        3. update_comment_meta($comment_id, $meta_key, $meta_value, $prev_value = '')
        4. delete_comment_meta($comment_id, $meta_key, $meta_value = '')
      14. wp_links
      15. wp_terms
      16. Functions Found in /wp-includes/taxonomy.php
        1. get_terms( $taxonomies, $args = '' )
        2. get_term( $term, $taxonomy, $output = OBJECT, $filter =
        3. wp_insert_term( $term, $taxonomy, $args = array() )
        4. wp_update_term( $term_id, $taxonomy, $args = array() )
        5. wp_delete_term( $term, $taxonomy, $args = array() )
      17. wp_term_taxonomy
      18. /wp-includes/taxonomy.php
        1. get_taxonomies( $args = array(), $output =
        2. get_taxonomy( $taxonomy )
        3. register_taxonomy( $taxonomy, $object_type, $args = array() )
      19. wp_term_relationships
        1. get_object_taxonomies( $object, $output =
        2. wp_get_object_terms( $object_ids, $taxonomies, $args = array() )
        3. wp_set_object_terms( $object_id, $terms, $taxonomy, $append = false )
    3. Extending WordPress
  5. 3. Leveraging WordPress Plugins
    1. The GPLv2 License
    2. Installing WordPress Plugins
    3. Building Your Own Plugin
    4. File Structure for an App Plugin
      1. /adminpages/
      2. /classes/
      3. /css/
      4. /js/
      5. /images/
      6. /includes/
      7. /includes/lib/
      8. /pages/
      9. /services/
      10. /scheduled/
      11. /schoolpress.php
    5. Add-Ons to Existing Plugins
    6. Use Cases and Examples
      1. The WordPress Loop
      2. WordPress Global Variables
        1. $wpdb
        2. Using custom DB tables
          1. Running queries
        3. Escaping in DB queries
        4. SELECT queries with $wpdb
          1. Insert, replace, and update
      3. Action Hooks
      4. Filters
    7. Free Plugins
      1. All in One SEO Pack
      2. BadgeOS
      3. Custom Post Type UI
      4. Posts 2 Posts
      5. Members
      6. W3 Total Cache
    8. Premium Plugins
      1. Gravity Forms
      2. Backup Buddy
      3. WP All Import
    9. Community Plugins
      1. BuddyPress
        1. Database tables
        2. Components
        3. Pages
        4. Settings
        5. Profile fields
        6. BuddyPress plugins
  6. 4. Themes
    1. Themes Versus Plugins
      1. When Developing Apps
      2. When Developing Plugins
      3. When Developing Themes
    2. The Template Hierarchy
    3. Page Templates
      1. Sample Page Template
      2. Using Hooks to Copy Templates
      3. When to Use a Theme Template
    4. Theme-Related WP Functions
      1. Using locate_template in Your Plugins
    5. Style.css
      1. Versioning Your Theme’s CSS Files
    6. Functions.php
    7. Themes and Custom Post Types
    8. Popular Theme Frameworks
      1. WP Theme Frameworks
        1. _s (Underscores)
        2. StartBox
        3. Genesis
      2. Non-WP Theme Frameworks
    9. Creating a Child Theme for StartBox
    10. Including Bootstrap in Your App’s Theme
    11. Menus
      1. Nav Menus
      2. Dynamic Menus
    12. Responsive Design
      1. Device and Display Detection in CSS
      2. Device and Feature Detection in JavaScript
        1. Detecting the screen and window size with JavaScript and jQuery
        2. Feature detection in JavaScript
      3. Device Detection in PHP
        1. Browser detection in WordPress core
        2. Browser detection with PHP’s get_browser()
      4. Final Note on Browser Detection
    13. Versioning CSS and JS Files
  7. 5. Custom Post Types, Post Metadata, and Taxonomies
    1. Default Post Types and Custom Post Types
      1. Page
      2. Post
      3. Attachment
      4. Revisions
      5. Nav Menu Item
    2. Defining and Registering Custom Post Types
      1. register_post_type( $post_type, $args );
        1. label
        2. labels
        3. menu_name
        4. description
        5. publicly_queryable
        6. exclude_from_search
        7. capability_type
        8. capabilities
        9. map_meta_cap
        10. hierarchical
        11. public
        12. rewrite
        13. has_archive
        14. query_var
        15. supports
        16. register_meta_box_cb
        17. permalink_epmask
        18. taxonomies
        19. show_ui
        20. menu_position
        21. menu_icon
        22. can_export
        23. show_in_nav_menus
        24. show_in_menu
        25. show_in_admin_bar
        26. delete_with_user
        27. _builtin
        28. _edit_link
    3. What Is a Taxonomy and How Should I Use It?
      1. Taxonomies Versus Post Meta
      2. Creating Custom Taxonomies
      3. register_taxonomy( $taxonomy, $object_type, $args )
        1. label
        2. labels
        3. hierarchical
        4. update_count_callback
        5. rewrite
        6. query_var
        7. public
        8. show_ui
        9. show_in_nav_menus
        10. show_tagcloud
        11. show_admin_column
        12. capabilities
      4. register_taxonomy_for_object_type( $taxonomy, $object_type )
    4. Using Custom Post Types and Taxonomies in Your Themes and Plugins
      1. The Theme Archive and Single Template Files
      2. Good Old WP_Query and get_posts()
    5. Metadata with CPTs
      1. add_meta_box( $id, $title, $callback, $screen, $context, $priority, $callback_args )
    6. Custom Wrapper Classes for CPTs
      1. Extending WP_Post Versus Wrapping It
      2. Why Use Wrapper Classes?
      3. Keep Your CPTs and Taxonomies Together
      4. Keep It in the Wrapper Class
      5. Wrapper Classes Read Better
  8. 6. Users, Roles, and Capabilities
    1. Getting User Data
    2. Add, Update, and Delete Users
    3. Hooks and Filters
    4. What Are Roles and Capabilities?
      1. Checking a User’s Role and Capabilities
      2. Creating Custom Roles and Capabilities
    5. Extending the WP_User Class
    6. Adding Registration and Profile Fields
    7. Customizing the Users Table in the Dashboard
    8. Plugins
      1. Theme My Login
      2. Hide Admin Bar from Non-Admins
      3. Paid Memberships Pro
      4. PMPro Register Helper
      5. Members
  9. 7. Other WordPress APIs, Objects, and Helper Functions
    1. Shortcode API
      1. Shortcode Attributes
      2. Nested Shortcodes
      3. Removing Shortcodes
      4. Other Useful Shortcode-Related Functions
    2. Widgets API
      1. Before You Add Your Own Widget
      2. Adding Widgets
      3. Defining a Widget Area
      4. Embedding a Widget Outside of a Dynamic Sidebar
    3. Dashboard Widgets API
      1. Removing Dashboard Widgets
      2. Adding Your Own Dashboard Widget
    4. Settings API
      1. Do You Really Need a Settings Page?
      2. Could You Use a Hook or Filter Instead?
      3. Use Standards When Adding Settings
      4. Ignore Standards When Adding Settings
    5. Rewrite API
      1. Adding Rewrite Rules
      2. Flushing Rewrite Rules
      3. Other Rewrite Functions
    6. WP-Cron
      1. Adding Custom Intervals
      2. Scheduling Single Events
      3. Kicking Off Cron Jobs from the Server
      4. Using Server Crons Only
    7. WP Mail
      1. Sending Nicer Emails with WordPress
    8. File Header API
      1. Adding File Headers to Your Own Files
      2. Adding New Headers to Plugins and Themes
  10. 8. Secure WordPress
    1. Why It’s Important
    2. Security Basics
      1. Update Frequently
      2. Don’t Use the Username “admin”
      3. Use a Strong Password
      4. Examples of Bad Passwords
      5. Examples of Good Passwords
    3. Hardening Your WordPress Install
      1. Don’t Allow Admins to Edit Plugins or Themes
      2. Change Default Database Tables Prefix
      3. Move wp-config.php
      4. Hide Login Error Messages
      5. Hide Your WordPress Version
      6. Don’t Allow Logins via wp-login.php
      7. Add Custom .htaccess Rules for Locking Down wp-admin
    4. Backup Everything!
    5. Scan Scan Scan!
    6. Useful Security Plugins
      1. Spam-Blocking Plugins
        1. Akismet
        2. Bad Behavior
      2. Backup Plugins
        1. Backup Buddy
        2. VaultPress
      3. Scanner Plugins
        1. WP Security Scan
        2. Exploit Scanner
        3. BBQ
        4. Antivirus-Once
      4. Login and Password-Protection Plugins
        1. Limit Login Attempts
        2. Ask Apache Password Protect
    7. Writing Secure Code
      1. Check User Capabilities
        1. user_can( $user, $capability )
        2. current_user_can( $capability )
        3. current_user_can_for_blog( $blog_id, $capability )
      2. Custom SQL Statements
      3. Data Validation, Sanitization, and Escaping
        1. esc_url( $url, $protocols = null, $_context =
        2. esc_url_raw( $url, $protocols = null )
        3. esc_html( $text )
        4. esc_js( $text )
        5. esc_attr( $text )
        6. esc_textarea( $text )
        7. sanitize_option( $option, $value )
        8. sanitize_text_field($str)
        9. sanitize_user( $username, $strict = false )
        10. sanitize_title( $title, $fallback_title = '' )
        11. sanitize_email( $email )
        12. sanitize_file_name( $filename )
        13. wp_kses( $string, $allowed_html, $allowed_protocols = array () )
      4. Nonces
        1. wp_create_nonce( $action = -1 )
        2. wp_verify_nonce($nonce, $action = -1)
        3. check_admin_referer($action = -1, $query_arg =
        4. wp_nonce_url( $actionurl, $action = -1 )
        5. wp_nonce_field( $action = -1, $name = “_wpnonce”, $referer = true , $echo = true )
        6. check_ajax_referer( $action = -1, $query_arg = false, $die = true )
  11. 9. JavaScript, jQuery, and AJAX
    1. What Is AJAX?
    2. What Is JSON?
    3. jQuery and WordPress
      1. Enqueuing Other JavaScript Libraries
      2. Where to Put Your Custom JavaScript
    4. AJAX Calls with WordPress and jQuery
    5. Managing Multiple AJAX Requests
    6. Heartbeat API
      1. Initialization
      2. Client-side JavaScript
      3. Server-side PHP
      4. Initialization
      5. Client-side JavaScript
      6. Server-side PHP
    7. WordPress Limitations with Asynchronous Processing
    8. Backbone.js
  12. 10. XML-RPC
    1. wp.getUsersBlogs
    2. wp.getPosts
    3. wp.getPost
    4. wp.newPost
    5. wp.editPost
    6. wp.deletePost
    7. wp.getTerms
    8. wp.getTerm
    9. wp.newTerm
    10. wp.editTerm
    11. wp.deleteTerm
    12. wp.getTaxonomies
    13. wp.getTaxonomy
    14. wp.getUsers
    15. wp.getUser
    16. wp.getProfile
    17. wp.editProfile
    18. wp.getCommentCount
    19. wp.getPageTemplates
    20. wp.getOptions
    21. wp.setOptions
    22. wp.getComment
    23. wp.getComments
    24. wp.deleteComment
    25. wp.editComment
    26. wp.newComment
    27. wp.getMediaLibrary
    28. wp.getMediaItem
    29. wp.uploadFile
    30. wp.getPostFormats
    31. wp.getPostType
    32. wp.getPostTypes
  13. 11. Mobile Apps with WordPress
    1. App Wrapper
    2. iOS Applications
      1. Enrolling as an Apple Developer
      2. Building Your App with Xcode
        1. Storyboard
        2. View controller
        3. iOS simulator
      3. App Distribution
      4. iOS Resources
    3. Android Applications
      1. AndroidManifest.xml
      2. activity_main.xml
        1. MainActivity.java
      3. Creating an APK file
      4. Getting Your App on Google Play
      5. Android Resources
    4. Extend Your App
    5. AppPresser
    6. Mobile App Use Cases
  14. 12. PHP Libraries, External APIs, and Web Services
    1. Imagick
    2. MaxMind GeoIP
    3. Google Maps JavaScript API v3
      1. Directions
      2. Distance Matrix
      3. Elevation
      4. Geocoding
      5. Street View Service
      6. Practical App
    4. Google Translate
    5. Google+
      1. People
      2. Activities
      3. Comments
      4. Moments
    6. Amazon Product Advertising API
      1. Request Parameters
      2. Operations
      3. Response Groups
    7. Twitter REST API v1.1
      1. Set Up Your App on Twitter.com
      2. Leverage a PHP Library
    8. Facebook
      1. Pictures
      2. Search
      3. Permissions
      4. Building an Application
      5. Leverage What’s Out There
    9. Twilio
    10. Microsoft Sharepoint
    11. We Missed a Few
  15. 13. Building WordPress Multisite Networks
    1. Why Multisite?
    2. Setting Up a Multisite Network
    3. Managing a Multisite Network
      1. Dashboard
      2. Sites
      3. Users
      4. Themes
      5. Plugins
      6. Settings
        1. Operational Settings
        2. Registration Settings
        3. New Site Settings
        4. Upload Settings
        5. Menu Settings
      7. Updates
    4. Multisite Database Structure
      1. Network-Wide Tables
        1. wp_blogs
        2. wp_blog_versions
        3. wp_registration_log
        4. wp_signups
        5. wp_site
        6. wp_sitemeta
      2. Individual Site Tables
      3. Shared Site Tables
    5. Multisite Plugins
      1. WordPress MU Domain Mapping
      2. Blog Copier
      3. More Privacy Options
      4. Multisite Global Search
      5. Multisite Robots.txt Manager
    6. Basic Multisite Functionality
      1. $blog_id
      2. is_multisite()
      3. get_current_blog_id()
      4. switch_to_blog( $new_blog )
      5. restore_current_blog()
      6. get_blog_details( $fields = null, $get_all = true )
      7. update_blog_details( $blog_id, $details = array() )
      8. get_blog_status( $id, $pref )
      9. update_blog_status( $blog_id, $pref, $value )
      10. get_blog_option( $id, $option, $default = false )
      11. update_blog_option( $id, $option, $value )
      12. delete_blog_option( $id, $option )
      13. get_blog_post( $blog_id, $post_id )
      14. add_user_to_blog( $blog_id, $user_id, $role )
      15. create_empty_blog( $domain, $path, $weblog_title, $site_id = 1 )
      16. Functions We Didn’t Mention
  16. 14. Localizing WordPress Apps
    1. Do You Even Need to Localize Your App?
    2. How Localization Is Done in WordPress
    3. Defining Your Locale in WordPress
    4. Prepping Your Strings with Translation Functions
      1. __($text, $domain = “default”)
      2. _e($text, $domain = “default”)
      3. _x($text, $context, $domain = “default”)
      4. _ex($title, $context, $domain = “default”)
      5. Escaping and Translating at the Same Time
    5. Creating and Loading Translation Files
      1. Our File Structure for Localization
      2. Generating a .pot File
      3. Creating a .po File
      4. Creating a .mo File
      5. Loading the Textdomain
    6. Localizing Nonstring Assets
  17. 15. Ecommerce
    1. Choosing a Plugin
      1. Shopping Cart Plugins
        1. Our favorite: Jigoshop
        2. Notable runner-up: WooCommerce
      2. Membership Plugins
        1. Our favorite: Paid Memberships Pro
      3. Digital Downloads
        1. Our favorite: Easy Digital Downloads
    2. Payment Gateways
    3. Merchant Accounts
    4. SSL Certificates and HTTPS
      1. Installing an SSL Certificate on Your Server
      2. SSL with Paid Memberships Pro
      3. SSL with Jigoshop
      4. WordPress Login and WordPress Admin over SSL
      5. WordPress Frontend over SSL
      6. SSL on Select Pages
      7. Avoiding SSL Errors with the “Nuclear Option”
    5. Setting Up Software as a Service (SaaS) with Paid Memberships Pro
    6. The Software as a Service Model
      1. Step 0: Figure Out How You Want to Charge for Your App
      2. Step 1: Installing and Activating Paid Memberships Pro
      3. Step 2: Setting Up the Level
      4. Step 3: Setting Up Pages
      5. Step 4: Payment Settings
      6. Step 5: Email Settings
      7. Step 6: Advanced Settings
      8. Step 7: Locking Down Pages
        1. Lock down a specific page
        2. Lock down a page by URL
        3. Lock down a portion of a page by shortcode
        4. Lock down a portion of a page by PHP code using the pmpro_hasMembershipLevel() function
      9. Step 8: Customizing Paid Memberships Pro
        1. Restricting nonmembers to the homepage
        2. Locking down files
        3. Change user roles based on membership levels
        4. International and long-form addresses
        5. Upgrade/downgrade pricing
  18. 16. WordPress Optimization and Scaling
    1. Terms
    2. Origin Versus Edge
    3. Testing
      1. What to Test
      2. Chrome Debug Bar
      3. Apache Bench
        1. Installing Apache Bench
        2. Running Apache Bench
        3. Testing with Apache Bench
        4. Graphing Apache Bench results with gnuplot
      4. Siege
      5. Blitz.io
    4. W3 Total Cache
      1. Page Cache Settings
      2. Minify
      3. Database Caching
      4. Object Cache
      5. CDNs
      6. GZIP Compression
    5. Hosting
      1. WordPress-Specific Hosts
      2. Rolling Your Own Server
        1. Apache server setup
        2. Nginx server setup
        3. Nginx in front of Apache
        4. MySQL optimization
        5. advanced-cache.php and object-cache.php
        6. Alternative PHP Cache (APC)
        7. Memcached
        8. Redis
        9. Varnish
        10. Batcache
    6. Selective Caching
      1. The Transient API
      2. Multisite Transients
    7. Using JavaScript to Increase Performance
    8. Custom Tables
    9. Bypassing WordPress
  19. Index
  20. Colophon
  21. Copyright