+353-1-416-8900REST OF WORLD
+44-20-3973-8888REST OF WORLD
1-917-300-0470EAST COAST U.S
1-800-526-8630U.S. (TOLL FREE)

Professional WordPress Plugin Development. Edition No. 2

  • Book

  • 480 Pages
  • June 2020
  • John Wiley and Sons Ltd
  • ID: 5837960

Extend WordPress with plugins using this advanced WordPress development book, updated for the current version

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.

Table of Contents

Introduction xxxi

Chapter 1: An Introduction to Plugins 1

What is a Plugin? 1

How Plugins Interact with WordPress 2

When are Plugins Loaded? 3

Available Plugins 4

Official Plugin Directory 4

Popular Plugin Examples 4

Popular Plugin Tags 5

Advantages of Plugins 5

Not Modifying Core 5

Why Reinvent the Wheel? 5

Separating Plugins and Themes 6

Easy Updates 7

Easier to Share and Reuse 7

Plugin Sandbox 7

Plugin Community 7

Installing and Managing Plugins 8

Installing a Plugin 8

Managing Plugins 9

Editing Plugins 9

Plugin Directories 9

Types of Plugins 10

Summary 11

Chapter 2: Plugin Framework 13

Requirements for Plugins 13

Naming Your Plugin 14

Using a Folder 14

Best Practices 14

Namespace Everything 14

File Organization 15

Folder Structure 16

Plugin Header 17

Creating the Header 17

Plugin License 18

Determining Paths 19

Plugin Paths 19

Local Paths 19

URL Paths 20

Activate/Deactivate Functions 22

Plugin Activation Function 22

Plugin Deactivation Function 23

Deactivate is Not Uninstall 23

Uninstall Methods 24

Why Uninstall is Necessary 24

Uninstall.php 24

Uninstall Hook 25

Coding Standards 25

Document Your Code 26

Naming Variables and Functions 27

Naming Classes and Methods 27

Naming Files 28

Single and Double Quotes 28

Indentation 28

Brace Style 29

Space Usage 29

Shorthand PHP 30

SQL Statements 30

Summary 30

Chapter 3: Dashboard And Settings 31

Adding Menus and Submenus 31

Creating a Top-Level Menu 32

Adding a Submenu 33

Adding a Menu Item to an Existing Menu 34

Plugin Settings 36

The Options API 36

Saving Options 36

Saving an Array of Options 37

Updating Options 37

Retrieving Options 38

Loading an Array of Options 39

Deleting Options 40

The Autoload Parameter 40

Segregating Plugin Options 41

Toggling the Autoload Parameter 42

The Settings API 42

Benefits of the Settings API 42

Settings API Functions 43

Creating the Plugin Administration Page 43

Registering New Settings 44

Defining Sections and Settings 44

Validating User Input 46

Rendering the Form 47

All Done! 48

Wrapping It Up: A Complete Plugin Management Page 48

Improving Feedback on Validation Errors 51

Expanding with Additional Field Types 52

Adding Fields to an Existing Page 59

How It Works 59

Adding a Section to an Existing Page 59

Adding Only Fields 60

WordPress’ Sections and Setting Fields 61

User Interface Concerns 62

Removing Settings 62

Keeping It Consistent 63

Using the WordPress UI 64

Headings 64

Dashicons 64

Messages 65

Buttons 66

Form Fields 67

Tables 68

Pagination 69

Summary 70

Chapter 4: Security And Performance 71

Security Overview 72

What Securing Your Plugin is 72

What Securing Your Plugin is Not 72

User Permissions 72

How to Check current_user_can() 73

Do Not Check Too Early 73

Nonces 74

Authority vs. Intention 74

What is a Nonce? 75

How to Create and Verify Nonces 75

Creating a Nonce URL 76

Creating a Nonce Field 76

Creating and Verifying a Nonce in a Plugin 77

Data Validation and Sanitization 78

The Need for Data Validation and Sanitization 78

Good Practice: Identifying Potentially Tainted Data 80

Validating or Sanitizing Input? 81

Validating and Sanitizing Cookbook 81

Integers 81

Arbitrary Text Strings 82

Key and Identifier Strings 83

Email Strings 84

URLs 84

HTML 86

JavaScript 88

Environment and Server Variables 88

Arrays of Data 89

Database Queries 89

Formatting SQL Statements 90

The $wpdb Object 90

Why wpdb Methods are Superior 91

All-in-One Methods 91

$wpdb->update() 92

$wpdb->insert() 92

Common Methods 93

Select a Variable 93

Select a Row 94

Select a Column 94

Select Generic Results 95

Generic Queries 96

Protecting Queries against SQL Injections 96

Security Good Habits 97

Performance Overview 97

Caching 98

Saving Cached Data 98

Loading and Using Cached Data 99

Deleting Cached Data 99

Caching Data within a Plugin 100

Transients 101

Saving an Expiring Option 102

Retrieving an Expiring Option 102

Deleting an Expiring Option 102

A Practical Example Using Transients 102

Technical Details 103

Transient Ideas 103

Summary 104

Chapter 5: Hooks 105

Understanding Hooks 105

Actions 106

What is an Action? 107

Action Hook Functions 108

remove_action() 108

remove_all_actions() 109

do_action_ref_array 110

has_action 111

did_action() 112

current_action 112

register_activation_hook and register_deactivation_hook 113

Commonly Used Action Hooks 113

plugins_loaded 113

init 114

admin_menu 115

save_post 116

wp_head 116

Filters 117

What is a Filter? 118

Filter Hook Functions 119

remove_filter 119

remove_all_filters 120

apply_filters_ref_array 121

has_filter 122

current_filter 122

Quick Return Functions 123

Commonly Used Filter Hooks 124

the_content 124

template_include 125

Using Hooks from within a Class 126

Using Hooks with Anonymous Functions 127

Creating Custom Hooks 128

Benefits of Creating Custom Hooks 128

Custom Action Hook Example 128

Custom Filter Hook Example 129

Finding Hooks 129

Searching for Hooks in the Core Code 130

Variable Hooks 130

Hook Reference Lists 130

Summary 131

Chapter 6: Javascript 133

Registering Scripts 134

Enqueueing Scripts 135

Limiting Scope 136

Localizing Scripts 136

Inline Scripts 137

Overview of Bundled Scripts 139

jQuery UI and Other Scripts 139

The WP Global 140

a11y Speak 140

Escaping 140

i18n 140

Heartbeat 141

Polyfills 141

Your Custom Scripts 141

jQuery 142

Benefits of Using jQuery 142

jQuery Crash Course 142

The jQuery Object 143

Syntax and Chaining 143

No-Conflict Mode in WordPress 144

Launching Code on Document Ready 144

Ajax 145

Backbone/Underscore 146

React 146

Summary 147

Chapter 7: Blocks And Gutenberg 149

What is Gutenberg? 149

Touring Gutenberg 151

Practical Examples 155

WooCommerce 156

The Events Calendar 157

Post Type Switcher 158

Technology Stack of Gutenberg 159

JavaScript 160

PHP 161

Node.js 162

webpack 163

Babel 163

React 163

JSX 163

ES6 163

“Hello World!” Block 164

PHP 164

JavaScript 164

webpack 165

Command Line 166

Activation 167

Wrap-Up 167

WP-CLI Scaffolding 168

Plugin 168

Blocks 169

Includes 169

Activation 169

Wrap-Up 169

create-guten-block Toolkit 170

Installation 171

Activation 171

Wrap-Up 173

Block Directory 173

Summary 174

Chapter 8: Content 175

Creating Custom Post Types 176

Post Type Possibilities 176

Registering a Post Type 177

register_post_type 177

Registering the Book Collection Post Type 177

Setting Post Type Labels 179

Using Custom Capabilities 180

Attaching Existing Taxonomies 182

Post Metadata 183

Registering Post Metadata 183

Adding Post Metadata 184

Retrieving Post Metadata 185

Updating Post Metadata 186

Deleting Post Metadata 186

Meta Boxes 187

What is a Meta Box? 187

Adding a Custom Meta Box 188

Saving Meta Box Data 190

Creating Custom Taxonomies 191

Understanding Taxonomies 192

Registering a Custom Taxonomy 192

register_taxonomy 193

Registering the Genre Taxonomy 193

Assigning a Taxonomy to a Post Type 194

Using Custom Taxonomies 195

Retrieving a Taxonomy 196

Using a Taxonomy with Posts 196

Taxonomy Conditional Tags 197

taxonomy_exists 197

is_taxonomy_hierarchical 198

is_tax 198

A Post Type, Post Metadata, and Taxonomy Plugin 199

Summary 204

Chapter 9: Users And User Data 205

Working with Users 206

User Functions 206

is_user_logged_in() 206

get_users() 207

count_users 207

Creating, Updating, and Deleting Users 208

Creating a New User 209

Updating an Existing User 211

Deleting an Existing User 212

User Data 213

Getting a User Object and Data 213

Getting the Current User Object 215

Getting User Post Counts 215

User Metadata 217

Adding User Metadata 218

Retrieving User Metadata 218

Updating User Metadata 219

Deleting User Metadata 220

Creating a Plugin with User Metadata 220

Roles and Capabilities 223

What are Roles and Capabilities? 223

Default Roles 224

Custom Roles 224

Limiting Access 225

Checking User Permissions 225

Is the User an Admin? 227

Customizing Roles 228

Creating a Role 228

Deleting a Role 230

Adding Capabilities to a Role 230

Removing Capabilities from a Role 231

A Custom Role and Capability Plugin 231

Summary 233

Chapter 10: Scheduled Tasks 235

What is Cron? 235

How is Cron Executed? 236

Scheduling Cron Events 236

Scheduling a Recurring Event 236

Scheduling a Single Event 238

Unscheduling an Event 240

Specifying Your Own Cron Intervals 241

Viewing Scheduled Cron Events 242

True Cron 247

Practical Use 247

The Blog Pester Plugin 247

Deleting Post Revisions Weekly 250

The Delete Comments Plugin 253

Summary 258

Chapter 11: Internationalization 259

Internationalization and Localization 260

Why Internationalize? 260

Understanding Internationalization in Professional Work 261

Getting Your Plugin Ready for Translation 261

Echoing and Returning Strings 262

The __() Function 262

The _e() Function 263

The esc_attr__() Function 263

The esc_attr_e() Function 264

The esc_html__() Function 264

The esc_html_e() Function 264

The _x() Function 264

The _ex() Function 265

The esc_attr_x() Function 266

The esc_html_x() Function 266

The _n() Function 267

The _nx() Function 268

The _n_noop() Function 269

The _nx_noop() Function 270

Using Placeholders 271

Internationalizing JavaScript 273

Developer Handbook Resource 275

Creating Translation Files 275

The MO and PO Files 276

Translation Tools 276

How to Create a POT File 277

Command Line 278

Where to Store Translation Files 278

Summary 278

Chapter 12: Rest Api 279

What the REST API is 279

What You Can Do with the REST API 280

Accessing the WordPress REST API 281

Default Endpoints 282

REST API Clients 283

Insomnia 283

Postman 283

Authentication 284

Enhanced Authentication 285

Custom Endpoints 286

The HTTP API 289

What is an HTTP Request? 289

HTTP Request Concepts 289

Dissecting an HTTP Transaction 289

Some Caveats on Checking HTTP Responses 291

Possibilities for Crafting HTTP Requests 292

How to Make HTTP Requests in PHP 292

Using the HTTP Extension 292

Using fopen() Streams 293

Using a Standard fopen() 293

Using fsockopen() 293

Using the CURL Extension 294

Too Many Ways? 294

WordPress’ HTTP Functions 294

The wp_remote_ Functions 294

wp_remote_* Input Parameters 295

wp_remote_* Return Values 297

wp_remote_ Companion Functions 302

Advanced Configuration and Tips 303

Proxy Support 303

Filtering Requests and Responses 304

Bringing It All Together 307

Create 307

Update 309

Delete 309

Resources 313

Summary 313

Chapter 13: Multisite 315

Terminology 316

Advantages of Multisite 317

Enabling Multisite in WordPress 317

Multisite Functions 319

The Site ID 319

Common Functions 319

Switching and Restoring Sites 321

Network Content Shortcode Examples 325

A Network Content Widget Example 330

Creating a New Site 336

Site Options 342

Network Options 342

Site Meta 343

Users and Roles 343

Super Admin 348

Checking the Site Owner 349

Network Stats 350

Database Schema 350

Multisite-Specific Tables 350

Site-Specific Tables 351

Query Classes 351

WP_Site_Query 351

WP_Network_Query 352

Object Classes 352

WP_Site 352

WP_Network 352

Summary 352

Chapter 14: The Kitchen Sink 353

Querying and Displaying Posts 353

Use Case for Displaying Posts 354

WP_Query Overview 354

The Loop 355

Shortcodes 358

What Shortcodes are 358

Register Custom Shortcodes 359

Building a Simple Shortcode 360

Building a Shortcode with Parameters 362

Building a Shortcode with Content 364

Shortcode Tips 366

Think Simplicity for the User 366

Remember That Shortcodes are Dynamic 366

Look under the Hood 367

remove_shortcode() 367

remove_all_shortcodes() 367

strip_shortcodes() 367

do_shortcode() 367

Widgets 368

Creating a Widget 368

Dashboard Widgets 377

Creating Dashboard Widgets 378

Creating a Dashboard Widget with Options 380

Rewrite Rules 384

Why Rewrite URLs 384

Permalink Principles 384

Search Engine Friendly 384

User Friendly 385

Apache’s mod_rewrite 385

URL Rewriting in WordPress 385

How WordPress Handles Queries 386

Overview of the Query Process 386

The Rewrite Object 387

The Query Object 388

What Plugins Can Do 389

Practical Uses 389

Rewriting a URL to Create a List of Shops 389

Creating a New Permalink Structure and Integrating Non-WordPress Pages 391

The Heartbeat API 395

What is the Heartbeat API? 395

Using the Heartbeat API 395

Sending Data 395

Receiving and Responding to Data 395

Processing the Response 396

Full Heartbeat API Plugin 396

Summary 398

Chapter 15: Debugging 399

Compatibility 399

Supporting Many WordPress Versions 400

Playing Nicely with Other WordPress Plugins 401

Keeping Current with WordPress Development 402

Deprecation 404

Dealing with Obsolete Client Installs 404

Debugging 405

Enabling Debugging 406

Displaying Debug Output 406

Understanding Debug Output 407

Error Logging 410

Enabling Error Logging 410

Setting Log File Location 411

Understanding the Log File 411

Query Monitor 411

Summary 414

Chapter 16: The Developer Toolbox 415

Core as Reference 415

PHP Inline Documentation 416

JavaScript Inline Documentation 417

Finding Functions 417

Common Core Files 418

formatting.php 418

functions.php 418

pluggable.php 419

plugin.php 419

post.php 419

user.php 420

Plugin Developer Handbook 420

Navigating the Handbook 420

Code Reference 420

Codex 421

Searching the Codex 421

Function Reference 422

Tool Websites 422

PHPXref 422

Hooks Database 423

Community Resources 424

Make WordPress 424

Support Forums 424

WordPress Slack 425

WordPress Development Updates 425

WordPress Ideas 426

Community News Sites 426

WordPress News 426

WordPress Planet 426

Post Status 426

Know the Code 426

LinkedIn Learning 427

Twitter 427

Local Events 427

Tools 427

Browser 427

Editor 428

NetBeans IDE 428

PhpStorm 428

Notepad++ 428

TextMate 428

Sublime Text 428

Visual Studio Code 429

Deploying Files with FTP, SFTP, and SSH 429

phpMyAdmin 429

Summary 430

Index 431

Authors

Brad Williams Justin Tadlock John James Jacoby