
Professional WordPress Plugin Development
Description
Alles über E-Books | Antworten auf Fragen rund um E-Books, Kopierschutz und Dateiformate finden Sie in unserem Info- & Hilfebereich.
This significantly updated edition of Professional WordPress Plugin Development addresses modern plugin development for WordPress, the highly popular content management system (CMS). If you're using WordPress to create and manage websites, WordPress plugins are the software that can extend or enhance CMS functionality. This book offers guidance on writing plugins for WordPress sites to share or sell to other users.
The second edition of Professional WordPress Plugin Development covers the building of advanced plugin development scenarios. It discusses the plugin framework and coding standards as well as dashboards, settings, menus, and related application programming interfaces (APIs). Additional topics include security, performance, data validation, and SQL statements.
* Learn about the power of hooks in WordPress
* Discover how JavaScript and Ajax will work in your site
* Understand key technologies: Block Editor/Gutenberg, JS/React, PHP, and the REST API
* Create and use custom post types and taxonomies.
* Creating custom dashboard menus and plugin settings
* Work with users and user data
* Schedule tasks and utilizing Cron
* Performance and security considerations
Written by experienced plugin developers, Professional WordPress Plugin Development also helps you internationalize and localize your WordPress website. Find out about debugging systems and optimizing your site for speed. As WordPress use continues to increase, you can elevate your professional knowledge of how to extend WordPress through plugins.
More details
Other editions
Additional editions

Persons
Brad Williams is CEO and cofounder of WebDevStudios, a WordPress design and development firm. He is coauthor of Professional WordPress Design and Development.
Justin Tadlock is a plugin and theme developer with over a decade of professional experience. He currently writes for WP Tavern.
John James Jacoby has authored dozens of popular WordPress plugins and leads the development of bbPress and BuddyPress. He has contributed to every major WordPress version since 2008.
Content
- Cover
- Title Page
- Copyright Page
- About the Authors
- Acknowledgments
- Contents
- Foreword
- Introduction
- Who This Book Is For
- What You Need to Use This Book
- What This Book Covers
- How This Book Is Structured
- Conventions
- Source Code
- Errata
- Chapter 1: An Introduction to Plugins
- What Is a Plugin?
- How Plugins Interact with WordPress
- When Are Plugins Loaded?
- Available Plugins
- Official Plugin Directory
- Popular Plugin Examples
- Popular Plugin Tags
- Advantages of Plugins
- Not Modifying Core
- Why Reinvent the Wheel?
- Separating Plugins and Themes
- Easy Updates
- Easier to Share and Reuse
- Plugin Sandbox
- Plugin Community
- Installing and Managing Plugins
- Installing a Plugin
- Managing Plugins
- Editing Plugins
- Plugin Directories
- Types of Plugins
- Summary
- Chapter 2: Plugin Framework
- Requirements for Plugins
- Naming Your Plugin
- Using a Folder
- Best Practices
- Namespace Everything
- File Organization
- Folder Structure
- Plugin Header
- Creating the Header
- Plugin License
- Determining Paths
- Plugin Paths
- Local Paths
- URL Paths
- Activate/Deactivate Functions
- Plugin Activation Function
- Plugin Deactivation Function
- Deactivate Is Not Uninstall
- Uninstall Methods
- Why Uninstall Is Necessary
- Uninstall.php
- Uninstall Hook
- Coding Standards
- Document Your Code
- Naming Variables and Functions
- Naming Classes and Methods
- Naming Files
- Single and Double Quotes
- Indentation
- Brace Style
- Space Usage
- Shorthand PHP
- SQL Statements
- Summary
- Chapter 3: Dashboard and Settings
- Adding Menus and Submenus
- Creating a Top-Level Menu
- Adding a Submenu
- Adding a Menu Item to an Existing Menu
- Plugin Settings
- The Options API
- Saving Options
- Saving an Array of Options
- Updating Options
- Retrieving Options
- Loading an Array of Options
- Deleting Options
- The Autoload Parameter
- Segregating Plugin Options
- Toggling the Autoload Parameter
- The Settings API
- Benefits of the Settings API
- Settings API Functions
- Creating the Plugin Administration Page
- Registering New Settings
- Defining Sections and Settings
- Validating User Input
- Rendering the Form
- All Done!
- Wrapping It Up: A Complete Plugin Management Page
- Improving Feedback on Validation Errors
- Expanding with Additional Field Types
- Adding Fields to an Existing Page
- How It Works
- Adding a Section to an Existing Page
- Adding Only Fields
- WordPress' Sections and Setting Fields
- User Interface Concerns
- Removing Settings
- Keeping It Consistent
- Using the WordPress UI
- Headings
- Dashicons
- Messages
- Buttons
- Form Fields
- Tables
- Pagination
- Summary
- Chapter 4: Security and Performance
- Security Overview
- What Securing Your Plugin Is
- What Securing Your Plugin Is Not
- User Permissions
- How to Check current_user_can()
- Do Not Check Too Early
- Nonces
- Authority vs. Intention
- What Is a Nonce?
- How to Create and Verify Nonces
- Creating a Nonce URL
- Creating a Nonce Field
- Creating and Verifying a Nonce in a Plugin
- Data Validation and Sanitization
- The Need for Data Validation and Sanitization
- Good Practice: Identifying Potentially Tainted Data
- Validating or Sanitizing Input?
- Validating and Sanitizing Cookbook
- Integers
- Arbitrary Text Strings
- Key and Identifier Strings
- Email Strings
- URLs
- HTML
- JavaScript
- Environment and Server Variables
- Arrays of Data
- Database Queries
- Formatting SQL Statements
- The $wpdb Object
- Why wpdb Methods Are Superior
- All-in-One Methods
- $wpdb-&update()
- $wpdb-&insert()
- Common Methods
- Select a Variable
- Select a Row
- Select a Column
- Select Generic Results
- Generic Queries
- Protecting Queries against SQL Injections
- Security Good Habits
- Performance Overview
- Caching
- Saving Cached Data
- Loading and Using Cached Data
- Deleting Cached Data
- Caching Data within a Plugin
- Transients
- Saving an Expiring Option
- Retrieving an Expiring Option
- Deleting an Expiring Option
- A Practical Example Using Transients
- Technical Details
- Transient Ideas
- Summary
- Chapter 5: Hooks
- Understanding Hooks
- Actions
- What Is an Action?
- Action Hook Functions
- remove_action()
- remove_all_actions()
- do_action_ref_array
- has_action
- did_action()
- current_action
- register_activation_hook and register_deactivation_hook
- Commonly Used Action Hooks
- plugins_loaded
- init
- admin_menu
- save_post
- wp_head
- Filters
- What Is a Filter?
- Filter Hook Functions
- remove_filter
- remove_all_filters
- apply_filters_ref_array
- has_filter
- current_filter
- Quick Return Functions
- Commonly Used Filter Hooks
- the_content
- template_include
- Using Hooks from within a Class
- Using Hooks with Anonymous Functions
- Creating Custom Hooks
- Benefits of Creating Custom Hooks
- Custom Action Hook Example
- Custom Filter Hook Example
- Finding Hooks
- Searching for Hooks in the Core Code
- Variable Hooks
- Hook Reference Lists
- Summary
- Chapter 6: JavaScript
- Registering Scripts
- Enqueueing Scripts
- Limiting Scope
- Localizing Scripts
- Inline Scripts
- Overview of Bundled Scripts
- jQuery UI and Other Scripts
- The WP Global
- a11y Speak
- Escaping
- i18n
- Heartbeat
- Polyfills
- Your Custom Scripts
- jQuery
- Benefits of Using jQuery
- jQuery Crash Course
- The jQuery Object
- Syntax and Chaining
- No-Conflict Mode in WordPress
- Launching Code on Document Ready
- Ajax
- Backbone/Underscore
- React
- Summary
- Chapter 7: Blocks and Gutenberg
- What Is Gutenberg?
- Touring Gutenberg
- Practical Examples
- WooCommerce
- The Events Calendar
- Post Type Switcher
- Technology Stack of Gutenberg
- JavaScript
- PHP
- Node.js
- webpack
- Babel
- React
- JSX
- ES6
- "Hello World!" Block
- PHP
- JavaScript
- webpack
- Command Line
- Activation
- Wrap-Up
- WP-CLI Scaffolding
- Plugin
- Blocks
- Includes
- Activation
- Wrap-Up
- create-guten-block Toolkit
- Installation
- Activation
- Wrap-Up
- Block Directory
- Summary
- Chapter 8: Content
- Creating Custom Post Types
- Post Type Possibilities
- Registering a Post Type
- register_post_type
- Registering the Book Collection Post Type
- Setting Post Type Labels
- Using Custom Capabilities
- Attaching Existing Taxonomies
- Post Metadata
- Registering Post Metadata
- Adding Post Metadata
- Retrieving Post Metadata
- Updating Post Metadata
- Deleting Post Metadata
- Meta Boxes
- What Is a Meta Box?
- Adding a Custom Meta Box
- Saving Meta Box Data
- Creating Custom Taxonomies
- Understanding Taxonomies
- Registering a Custom Taxonomy
- register_taxonomy
- Registering the Genre Taxonomy
- Assigning a Taxonomy to a Post Type
- Using Custom Taxonomies
- Retrieving a Taxonomy
- Using a Taxonomy with Posts
- Taxonomy Conditional Tags
- taxonomy_exists
- is_taxonomy_hierarchical
- is_tax
- A Post Type, Post Metadata, and Taxonomy Plugin
- Summary
- Chapter 9: Users and User Data
- Working with Users
- User Functions
- is_user_logged_in()
- get_users()
- count_users
- Creating, Updating, and Deleting Users
- Creating a New User
- Updating an Existing User
- Deleting an Existing User
- User Data
- Getting a User Object and Data
- Getting the Current User Object
- Getting User Post Counts
- User Metadata
- Adding User Metadata
- Retrieving User Metadata
- Updating User Metadata
- Deleting User Metadata
- Creating a Plugin with User Metadata
- Roles and Capabilities
- What Are Roles and Capabilities?
- Default Roles
- Custom Roles
- Limiting Access
- Checking User Permissions
- Is the User an Admin?
- Customizing Roles
- Creating a Role
- Deleting a Role
- Adding Capabilities to a Role
- Removing Capabilities from a Role
- A Custom Role and Capability Plugin
- Summary
- Chapter 10: Scheduled Tasks
- What Is Cron?
- How Is Cron Executed?
- Scheduling Cron Events
- Scheduling a Recurring Event
- Scheduling a Single Event
- Unscheduling an Event
- Specifying Your Own Cron Intervals
- Viewing Scheduled Cron Events
- True Cron
- Practical Use
- The Blog Pester Plugin
- Deleting Post Revisions Weekly
- The Delete Comments Plugin
- Summary
- Chapter 11: Internationalization
- Internationalization and Localization
- Why Internationalize?
- Understanding Internationalization in Professional Work
- Getting Your Plugin Ready for Translation
- Echoing and Returning Strings
- The __() Function
- The _e() Function
- The esc_attr__() Function
- The esc_attr_e() Function
- The esc_html__() Function
- The esc_html_e() Function
- The _x() Function
- The _ex() Function
- The esc_attr_x() Function
- The esc_html_x() Function
- The _n() Function
- The _nx() Function
- The _n_noop() Function
- The _nx_noop() Function
- Using Placeholders
- Internationalizing JavaScript
- Developer Handbook Resource
- Creating Translation Files
- The MO and PO Files
- Translation Tools
- How to Create a POT File
- Command Line
- Where to Store Translation Files
- Summary
- Chapter 12: REST API
- What the REST API Is
- What You Can Do with the REST API
- Accessing the WordPress REST API
- Default Endpoints
- REST API Clients
- Insomnia
- Postman
- Authentication
- Enhanced Authentication
- Custom Endpoints
- The HTTP API
- What Is an HTTP Request?
- HTTP Request Concepts
- Dissecting an HTTP Transaction
- Some Caveats on Checking HTTP Responses
- Possibilities for Crafting HTTP Requests
- How to Make HTTP Requests in PHP
- Using the HTTP Extension
- Using fopen() Streams
- Using a Standard fopen()
- Using fsockopen()
- Using the CURL Extension
- Too Many Ways?
- WordPress' HTTP Functions
- The wp_remote_ Functions
- wp_remote_* Input Parameters
- wp_remote_* Return Values
- wp_remote_ Companion Functions
- Advanced Configuration and Tips
- Proxy Support
- Filtering Requests and Responses
- Bringing It All Together
- Create
- Update
- Delete
- Resources
- Summary
- Chapter 13: Multisite
- Terminology
- Advantages of Multisite
- Enabling Multisite in WordPress
- Multisite Functions
- The Site ID
- Common Functions
- Switching and Restoring Sites
- Network Content Shortcode Examples
- A Network Content Widget Example
- Creating a New Site
- Site Options
- Network Options
- Site Meta
- Users and Roles
- Super Admin
- Checking the Site Owner
- Network Stats
- Database Schema
- Multisite-Specific Tables
- Site-Specific Tables
- Query Classes
- WP_Site_Query
- WP_Network_Query
- Object Classes
- WP_Site
- WP_Network
- Summary
- Chapter 14: The Kitchen Sink
- Querying and Displaying Posts
- Use Case for Displaying Posts
- WP_Query Overview
- The Loop
- Shortcodes
- What Shortcodes Are
- Register Custom Shortcodes
- Building a Simple Shortcode
- Building a Shortcode with Parameters
- Building a Shortcode with Content
- Shortcode Tips
- Think Simplicity for the User
- Remember That Shortcodes Are Dynamic
- Look under the Hood
- remove_shortcode()
- remove_all_shortcodes()
- strip_shortcodes()
- do_shortcode()
- Widgets
- Creating a Widget
- Dashboard Widgets
- Creating Dashboard Widgets
- Creating a Dashboard Widget with Options
- Rewrite Rules
- Why Rewrite URLs
- Permalink Principles
- Search Engine Friendly
- User Friendly
- Apache's mod_rewrite
- URL Rewriting in WordPress
- How WordPress Handles Queries
- Overview of the Query Process
- The Rewrite Object
- The Query Object
- What Plugins Can Do
- Practical Uses
- Rewriting a URL to Create a List of Shops
- Non-WordPress Pages
- The Heartbeat API
- What Is the Heartbeat API?
- Using the Heartbeat API
- Sending Data
- Receiving and Responding to Data
- Processing the Response
- Full Heartbeat API Plugin
- Summary
- Chapter 15: Debugging
- Compatibility
- Supporting Many WordPress Versions
- Playing Nicely with Other WordPress Plugins
- Keeping Current with WordPress Development
- Deprecation
- Dealing with Obsolete Client Installs
- Debugging
- Enabling Debugging
- Displaying Debug Output
- Understanding Debug Output
- Error Logging
- Enabling Error Logging
- Setting Log File Location
- Understanding the Log File
- Query Monitor
- Summary
- Chapter 16: The Developer Toolbox
- Core as Reference
- PHP Inline Documentation
- JavaScript Inline Documentation
- Finding Functions
- Common Core Files
- formatting.php
- functions.php
- pluggable.php
- plugin.php
- post.php
- user.php
- Plugin Developer Handbook
- Navigating the Handbook
- Code Reference
- Codex
- Searching the Codex
- Function Reference
- Tool Websites
- PHPXref
- Hooks Database
- Community Resources
- Make WordPress
- Support Forums
- WordPress Slack
- WordPress Development Updates
- WordPress Ideas
- Community News Sites
- WordPress News
- WordPress Planet
- Post Status
- Know the Code
- LinkedIn Learning
- Local Events
- Tools
- Browser
- Editor
- NetBeans IDE
- PhpStorm
- Notepad++
- TextMate
- Sublime Text
- Visual Studio Code
- Deploying Files with FTP, SFTP, and SSH
- phpMyAdmin
- Summary
- Index
- EULA
1
An Introduction to Plugins
WHAT'S IN THIS CHAPTER?
- Understanding what a plugin is
- Using available WordPress APIs
- Finding examples of popular plugins
- Separating plugin and theme functionality
- Managing and installing plugins
- Understanding types of WordPress plugins
WordPress is the most popular open source content management system available today. One of the primary reasons WordPress is so popular is the ease with which you can customize and extend WordPress through plugins. WordPress has an amazing framework in place that gives plugin developers the tools needed to extend WordPress in any way imaginable.
Understanding how plugins work, and the tools available in WordPress, is critical knowledge when developing professional WordPress plugins.
WHAT IS A PLUGIN?
A plugin in WordPress is a PHP-based script that extends or alters the core functionality of WordPress. Quite simply, plugins are files installed in WordPress to add a feature, or set of features, to WordPress. Plugins can range in complexity from a simple social networking plugin to an extremely elaborate eCommerce package. There is no limit to what a plugin can do in WordPress; because of this, there is no shortage of plugins available for download.
How Plugins Interact with WordPress
WordPress features many different APIs for use in your plugin. Each API, or application programming interface, helps interact with WordPress in a different way. The following are the main available APIs in WordPress and their function:
- Plugin: Provides a set of hooks that enable plugins access to specific parts of WordPress. WordPress contains two different types of hooks: Actions and Filters. The Action hook enables you to trigger custom plugin code at specific points during execution. For example, you can trigger a custom function to run after a user registers a user account in WordPress. The Filter hook modifies text before adding it to or after retrieving it from the database.
- Widgets: Allows you to create and manage widgets in your plugin. Widgets appear under the Appearance ? Widgets screen and are available to add to any registered sidebar in your theme. The API enables multiple instances of the same widget to be used throughout your sidebars.
- Shortcode: Adds shortcode support to your plugin. A shortcode is a simple hook that enables you to call a PHP function by adding something such as [shortcode] to a post or page.
- HTTP: Sends HTTP requests from your plugin. This API retrieves content from an external URL or for submitting content to a URL. Currently you have five different ways to send an HTTP request. This API standardizes that process and tests each method prior to executing. Based on your server configuration, the API will use the appropriate method and make the request.
- REST API: Allows developers to interact with your WordPress website remotely by sending and receiving JavaScript Object Notation (JSON) objects. You can create, read, update, and delete (CRUD) content within WordPress. The REST API is covered extensively in Chapter 12, "REST API."
- Settings: Inserts settings or a settings section for your plugin. The primary advantage to using the Settings API is security. All settings data is scrubbed, so you do not need to worry about cross-site request forgery (CSRF) and cross-site scripting (XSS) attacks when saving plugin settings.
- Options: Stores and retrieves options in your plugin. This API features the capability to create new options, update existing options, delete options, and retrieve any option already defined.
- Dashboard Widgets: Creates Dashboard widgets. Widgets automatically appear on the WordPress Dashboard and contain all standard customization features including minimize, drag/drop, and screen options for hiding.
- Rewrite: Creates custom rewrite rules in your plugin. This API enables you to add static endpoints (
/custom-page/), structure tags (%postname%), and feed links (/feed/json/). - Transients: Creates temporary options (cached data) in your plugins. This API is similar to the Options API, but all options are saved with an expiration time.
- Database: Accesses the WordPress database. This includes creating, updating, deleting, and retrieving database records for use in your plugins.
- Theme Customization (Customize) API: Adds custom website and theme options to the WordPress Customizer. Theme customizations are displayed in a real-time preview prior to publishing to the live website.
There are additional, lesser known APIs that exist within the WordPress Core software. To view a full list, visit the Core Developer Handbook:
https://make.wordpress.org/core/handbook/best-practices/core-apis
WordPress also features pluggable functions. These functions enable you to override specific core functions in a plugin. For example, the wp_mail() function is a pluggable function. You can easily define this function in your plugin and send email using the Simple Mail Transfer Protocol (SMTP) rather than the default method. All pluggable functions are defined in the /wp-includes/pluggable.php WordPress Core file.
As an example, let's look at the wp_mail() pluggable function, which starts with this line of code:
if ( ! function_exists( 'wp_mail' ) ) : You can see that the code first checks to see whether a wp_mail() function already exists using the function_exists() PHP function. If you created your own custom wp_mail() function, that will be used; if not, the WordPress Core version of wp_mail() will be used.
WARNING Pluggable functions are no longer being added to WordPress Core. Newer functions utilize hooks for overriding their functionality.
You can use some predefined functions during specific plugin tasks, such as when a plugin is activated or deactivated and even when a plugin is uninstalled. Chapter 2, "Plugin Framework," covers these functions in detail.
When Are Plugins Loaded?
Plugins are loaded early in the process when a WordPress-powered web page is called. Figure 1-1 shows a high-level diagram of the standard loading process when loading a page in WordPress.
FIGURE 1-1: Loading a page in WordPress
The flow changes slightly when loading an admin page. The differences are minor and primarily concern what theme is loaded: admin theme versus your website theme.
AVAILABLE PLUGINS
When researching available plugins, you need to know where to find WordPress plugins. You can download plugins from many places on the Internet, but this isn't always a good idea.
WARNING As with any software, downloading plugins from an untrusted source could lead to malware-injected and compromised plugin files. It's best to download plugins only from trusted websites and official sources such as the official Plugin Directory.
Official Plugin Directory
The first place to start when researching available WordPress plugins is the official Plugin Directory at WordPress.org. The Plugin Directory is located at https://wordpress.org/plugins. With more than 55,000 plugins available and millions of plugin downloads, it's easy to see the vital role plugins play in every WordPress website. All plugins available in the Plugin Directory are 100 percent GPL and free to use for personal or commercial use.
Popular Plugin Examples
Take a look at some of the more popular WordPress plugins available to get a sense of their diversity:
- Yoast SEO: Advanced search engine optimization functionality for WordPress. Features include custom metadata for all content, canonical URLs, custom post type support, XML sitemaps, and more!
- WPForms: A powerful drag-and-drop form builder. Create simple contact forms and powerful subscription payment forms, all without writing a single line of code.
- BuddyPress: A suite of components used to bring common social networking features to your website. Features for online communities include member profiles, activity streams, user groups, messaging, and more!
- WooCommerce: Advanced eCommerce solution built on WordPress. This is an extremely powerful plugin allowing anyone to sell physical and digital goods online.
- Custom Post Type UI: Easy-to-use interface for registering and managing custom post types and taxonomies in WordPress.
As you can see, the preceding plugins can handle a variety of complex tasks. The features added by these plugins are universal and features that many websites on the Internet could...
System requirements
File format: ePUB
Copy protection: Adobe-DRM (Digital Rights Management)
System requirements:
- Computer (Windows; MacOS X; Linux): Install the free reader Adobe Digital Editions prior to download (see eBook Help).
- Tablet/smartphone (Android; iOS): Install the free app Adobe Digital Editions or the app PocketBook before downloading (see eBook Help).
- E-reader: Bookeen, Kobo, Pocketbook, Sony, Tolino and many more (not Kindle).
The file format ePub works well for novels and non-fiction books – i.e., „flowing” text without complex layout. On an e-reader or smartphone, line and page breaks automatically adjust to fit the small displays.
This eBook uses Adobe-DRM, a „hard” copy protection. If the necessary requirements are not met, unfortunately you will not be able to open the eBook. You will therefore need to prepare your reading hardware before downloading.
Please note: We strongly recommend that you authorise using your personal Adobe ID after installation of any reading software.
For more information, see our ebook Help page.