WordPress Plugin Development Cookbook, - Yannick Lefebvre - E-Book

WordPress Plugin Development Cookbook, E-Book

Yannick Lefebvre

0,0
27,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

WordPress is one of the most widely used, powerful, and open content management systems (CMSs). Whether you're a site owner trying to find the right extension, a developer who wants to contribute to the community, or a website developer working to fulfill a client's needs, learning how to extend WordPress' capabilities will help you to unleash its full potential. This book will help you become familiar with API functions to create secure plugins with easy-to-use administration interfaces.
This third edition contains new recipes and up-to-date code samples, including new chapters on creating custom blocks for the block editor and integrating data from external sources. From one chapter to the next, you’ll learn how to create plugins of varying complexity, ranging from a few lines of code to complex extensions that provide intricate new capabilities. You'll start by using the basic mechanisms provided in WordPress to create plugins, followed by recipes covering how to design administration panels, enhance the post editor with custom fields, store custom data, and even create custom blocks. You'll safely incorporate dynamic elements into web pages using scripting languages, learn how to integrate data from external sources, and build new widgets that users will be able to add to WordPress sidebars and widget areas.
By the end of this book, you will be able to create WordPress plugins to perform any task you can imagine.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 455

Veröffentlichungsjahr: 2022

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



WordPress Plugin Development Cookbook

Third Edition

Explore the complete set of tools to craft powerful plugins that extend the world's most popular CMS

Yannick Lefebvre

BIRMINGHAM—MUMBAI

WordPress Plugin Development Cookbook

Third Edition

Copyright © 2022 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Pavan Ramchandani

Publishing Product Manager: Kaustubh Manglurkar

Senior Editor: Aamir Ahmed

Content Development Editor: Feza Shaikh

Technical Editor: Shubham Sharma

Copy Editor: Safis Editing

Project Coordinator: Manthan Patel

Proofreader: Safis Editing

Indexer: Manju Arasan

Production Designer: Prashant Ghare

Marketing Coordinator: Anamika Singh

First published: July 2012

Second edition: July 2017

Third edition: March 2022

Production reference: 1170222

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-80181-077-7

www.packt.com

To my wife, Andrée, for her everlasting love, her patience throughout the writing process, and supporting all my quirks.

To my daughters, Évelyne and Gabrielle, for always making me smile and becoming wonderful women.

To the users of my WordPress plugins, who are always pushing me to learn new things and add great new features to my creations after all these years.

– Yannick Lefebvre

Contributors

About the author

Yannick Lefebvre is a plugin developer who has created multiple plugins on the official WordPress repository. His first creation, Link Library, is used on thousands of sites worldwide. With a background in computer science, he wrote his first plugin in 2004 and quickly started sharing his creations with the community. He is actively involved in the Montreal WordPress community, has presented multiple times at WordCamp Montreal, and offers custom plugin development services. By day, Yannick works for CM Labs Simulations, a company providing software tools and simulators for vehicles and heavy equipment.

I would like to thank the WordCamp Montreal organizers for giving me the chance to speak at multiple editions of the event, for creating great videos of the presentations, and for giving me the opportunity to get involved in the community. This project would not have existed without them.

I would also like to thank Richard Archambault for his great feedback and encouragement while I wrote the first edition of this book, as well as the entire Packt Publishing team for proposing this great project to me, supporting me through the entire process, and allowing me to put together this third edition.

Finally, I would like to thank my parents for always believing in me and encouraging me in all my projects.

About the reviewers

Ali Demirci is a senior developer who has 15 years of experience in WordPress. He started working on WordPress in 2007. He is the co-founder of 2035themes. He has sold more than 6,000 WordPress themes on Themeforest. He became a freelancer as the themes business wasn't providing a stable income. He is now a full-time freelancer on the Codeable platform.

Stefan C. Densmore has been a WordPress developer since 2003 and a continuous member of the WPMUDEV development community since 2011. He has been a speaker at multiple WordCamps as a subject matter expert in WordPress Multisite development. With a formal education in human factors engineering and performance psychology, Stefan is passionate about making complex systems more user-friendly. He has a fondness for applications and plugins that enhance information sharing and knowledge management. Stefan has served as a technology broker and consultant for various information management interests and lives in the United States. He is the founder of both the United Resource Connection and Cybercasemanager enterprises, and can be found on Twitter @StefanDensmore.

Fred Atkinson is a telecom/IT professional with interests in web and internet technologies and website development. As an avid ham radio operator (WB4AEJ, for 47 years), he has been using WordPress for several years to build websites that facilitate the propagation of operator callsigns. He studied at Johns Hopkins University, earning a master's degree in Information and Telecommunications Systems Management in 1997. He also has an associate's degree in Enterprise Network Management from Stratford University. He is now retired and currently lives in Mesa, Arizona.

Table of Contents

Preface

Chapter 1: Preparing a Local Development Environment

Technical requirements

Installing a local web server on your computer

How to do it…

How it works…

There's more…

Creating a local version control repository

How to do it…

How it works…

There's more…

Installing a dedicated code editor/text editor

Getting ready

How to do it…

How it works…

There's more…

Chapter 2: Plugin Framework Basics

Technical requirements  

Creating a plugin file and header

Getting ready

How to do it...

How it works...

See also

Adding output content to page headers using plugin actions

How to do it...

How it works...

There's more...

See also

Using WordPress path utility functions to load external files and images

How to do it...

How it works...

There's more...

See also

Modifying the site generator meta tag using plugin filters

How to do it...

How it works...

There's more...

See also

Adding text after each item's content using plugin filters

How to do it...

How it works...

There's more...

See also

Inserting link tracking code in the page body using plugin filters

Getting ready

How to do it...

How it works...

See also

Troubleshooting coding errors and printing variable content

How to do it...

How it works...

There's more...

See also

Creating a new simple shortcode

How to do it...

How it works...

See also

Creating a new shortcode with parameters

How to do it...

How it works...

See also

Creating a new enclosing shortcode

How to do it...

How it works...

See also

Loading a style sheet to format plugin output

Getting ready

How to do it...

How it works...

See also

Writing plugins using object-oriented PHP

Getting ready

How to do it...

How it works...

There's more…

See also

Chapter 3: User Settings and Administration Pages

Technical requirements

Creating default user settings on plugin initialization

How to do it...

How it works...

There's more...

See also

Storing user settings using arrays

Getting ready

How to do it...

How it works...

See also

Removing plugin data on deletion

Getting ready

How to do it...

How it works...

See also

Creating an administration page menu item in the settings menu

Getting ready

How to do it...

How it works...

There's more...

See also

Creating a multi-level administration menu

How to do it...

How it works...

There's more…

See also

Rendering the admin page contents using HTML

Getting ready

How to do it...

How it works...

There's more...

See also

Processing and storing plugin configuration data

Getting ready

How to do it...

How it works...

See also

Displaying a confirmation message when options are saved

Getting ready

How to do it...

How it works...

See also

Adding custom help pages

Getting ready

How to do it...

How it works...

See also

Rendering the admin page contents using the Settings API

How to do it...

How it works...

There's more...

See also

Accessing user settings from action and filter hooks

Getting ready

How to do it...

How it works...

See also

Formatting admin pages using meta boxes

Getting ready

How to do it...

How it works...

See also

Splitting admin code from the main plugin file to optimize site performance

Getting ready

How to do it...

How it works...

See also

Storing style sheet data in user settings

Getting ready

How to do it...

How it works...

See also

Managing multiple sets of user settings from a single admin page

Getting ready

How to do it...

How it works...

See also

Creating a network-level plugin with admin pages

Getting ready

How to do it...

How it works...

See also

Chapter 4: The Power of Custom Post Types

Technical requirements

Creating a custom post type

Getting ready

How to do it...

How it works...

There's more...

See also

Adding a new section to the custom post type editor

Getting ready

How to do it...

How it works...

See also

Displaying single custom post type items using a custom layout

Getting ready

How to do it...

How it works...

See also

Tailoring search output for custom post type items

Getting ready

How to do it…

How it works…

See also

Displaying custom post type data in shortcodes

Getting ready

How to do it...

How it works...

See also

Adding custom categories for custom post types

Getting ready

How to do it...

How it works...

See also

Adding custom fields to categories

Getting ready

How to do it...

How it works...

See also

Hiding the category editor from the custom post type editor

Getting ready

How to do it...

How it works...

See also

Displaying additional columns in the custom post list page

Getting ready

How to do it...

How it works...

See also

Adding filters for custom categories to the custom post list page

Getting ready

How to do it...

How it works...

See also

Adding Quick Edit fields for custom categories

Getting ready

How to do it...

How it works...

Updating the page title to include custom post data using plugin filters

Getting ready

How to do it...

How it works...

Chapter 5: Customizing Post and Page Editors

Technical requirements

Capturing and displaying information using custom meta boxes

Getting ready

How to do it...

How it works...

There's more...

Displaying custom post data using filter functions

Getting ready

How to do it...

How it works...

See also

Hiding the Custom Fields section in the post editor

Getting ready

How to do it...

How it works...

Extending the post editor to attach custom files with the media uploader

Getting ready

How to do it...

How it works...

See also

Chapter 6: Extending the Block Editor

Technical requirements

Setting up a block development environment and creating a simple block

Getting ready

How to do it...

How it works...

There's more...

See also

Creating an editable blockquote block

Getting ready

How to do it...

How it works...

See also

Creating a new WordPress REST endpoint

Getting ready

How to do it...

How it works...

See also

Creating a server-side rendering block that leverages an existing shortcode

Getting ready

How to do it...

How it works...

See also

Chapter 7: Accepting User Content Submissions

Technical requirements

Creating a client-side content submission form

Getting ready

How to do it...

How it works...

See also

Saving user-submitted content in custom post types

Getting ready

How to do it...

How it works...

There's more...

See also

Sending email notifications upon new submissions

Getting ready

How to do it...

How it works...

See also

Implementing a CAPTCHA on user forms using an online service

Getting ready

How to do it...

How it works...

See also

Using a local library to implement a CAPTCHA on user forms

Getting ready

How to do it...

How it works...

See also

Chapter 8: Customizing User Data

Technical requirements

Adding custom fields to the user editor

Getting ready

How to do it...

How it works...

See also

Processing and storing custom user data

Getting ready

How to do it...

How it works...

See also

Displaying new user data on the user list page

Getting ready

How to do it...

How it works...

See also

Using custom user data in an enclosing shortcode

Getting ready

How to do it...

How it works...

See also

Chapter 9: Leveraging JavaScript, jQuery, and AJAX Scripts

Technical requirements

Safely loading jQuery onto WordPress web pages

Getting ready

How to do it...

How it works...

There's more...

Displaying a pop-up dialog using the built-in ThickBox plugin

Getting ready

How to do it...

How it works...

There's more...

Controlling pop-up dialog display using shortcodes

Getting ready

How to do it...

How it works...

See also

Displaying a calendar day selector using the Datepicker plugin

Getting ready

How to do it...

How it works...

Adding tooltips to admin page form fields using the TipTip plugin

Getting ready

How to do it...

How it works...

See also

Using AJAX to dynamically update partial page contents

Getting ready

How to do it...

How it works...

See also

Chapter 10: Adding New Widgets to the WordPress Library

Technical requirements

Creating a new widget in WordPress

Getting ready

How to do it...

How it works...

See also

Displaying widget configuration options

Getting ready

How to do it...

How it works...

See also

Validating widget configuration options

Getting ready

How to do it...

How it works...

See also

Adding a custom dashboard widget

Getting ready

How to do it...

How it works...

See also

Adding a custom widget to the network dashboard

Getting ready

How to do it...

How it works...

See also

Chapter 11: Fetching, Caching, and Regularly Updating External Site Data

Technical requirements

Displaying RSS items from an external feed

Getting ready

How to do it…

How it works...

There's more…

See also

Optimizing plugin performance by storing external data using transients

Getting ready

How to do it...

How it works...

See also

Scheduling plugin data updates using WP-Cron

Getting ready

How to do it...

There's more…

See also

Chapter 12: Enabling Plugin Internationalization

Technical requirements

Changing the WordPress site language configuration

Getting ready

How to do it...

How it works...

Adapting default user settings for translation

Getting ready

How to do it...

How it works...

See also

Making admin page code ready for translation

Getting ready

How to do it...

How it works...

See also

Modifying shortcode output for translation

Getting ready

How to do it...

How it works...

See also

Translating text strings using Poedit

Getting ready

How to do it...

How it works...

There's more...

See also

Loading a language file in the plugin initialization

Getting ready

How to do it...

How it works...

There's more...

See also

Chapter 13: Distributing Your Plugin on WordPress.org

Technical requirements

Creating a README file for your plugin

Getting ready

How to do it...

How it works...

There's more...

Applying for your plugin to be hosted on WordPress.org

How to do it...

How it works...

See also

Uploading your plugin using Subversion

Getting ready

How to do it...

How it works...

There's more...

See also

Providing plugin banner and thumbnail images

Getting ready

How to do it...

How it works...

See also

Other Books You May Enjoy

Preface

As it approaches the twentieth anniversary of its initial release, WordPress continues to be one of the most widely used, powerful, and open content management systems (CMSs). Whether you're a site owner trying to find the right extension, a developer who wants to contribute to the community, or a website developer working to fulfill a client's needs, learning how to extend WordPress' capabilities will help you to unleash its full potential.

This book will help you become familiar with API functions to create secure plugins with easy-to-use administration interfaces. Complete with new recipes and up-to-date code samples, including new chapters on the creation of custom blocks for the Block Editor and interacting with external data sources, this third-edition WordPress plugin development book teaches you how to create plugins of varying complexity ranging from using just a few lines of code to complex extensions that provide intricate new capabilities.

Starting with WordPress' basic mechanism for creating plugins, the book covers recipes to show you how to design administration panels, enhance the post editor with custom fields, store custom data, and even create custom blocks. You'll safely incorporate dynamic elements into web pages using scripting languages, learn how to integrate data from external sources, and build new widgets that can be added to WordPress sidebars and widget areas. By the end of this book, you'll be able to create WordPress plugins to perform almost any task you can imagine.

Who this book is for

This book is for WordPress users, developers, and site integrators interested in creating new plugins to address their personal needs, fulfill client requirements, and bring new capabilities to the WordPress community. Basic knowledge of PHP and WordPress is expected.

What this book covers

Chapter 1, Preparing a Local Development Environment, shows plugin developers how to install and configure an efficient development environment.

Chapter 2, Plugin Framework Basics, explains the basic mechanics of registering user functions with WordPress to be executed at key points when web pages are displayed, forming the basis of plugin creation.

Chapter 3, User Settings and Administration Pages, covers the creation of administration pages that will allow users to configure the plugins you create.

Chapter 4, The Power of Custom Post Types, empowers developers to add whole new content management sections to the WordPress environment.

Chapter 5, Customizing Post and Page Editors, demonstrates how to alter the default administration post and page editing environment to add new capabilities.

Chapter 6, Extending the Block Editor, shows how to create new content blocks for the new Block Editor and facilitate building websites.

Chapter 7, Accepting User Content Submissions, allows users to submit their own content to new content sections that will be managed by your plugins.

Chapter 8, Customizing User Data, explains how to store additional information for users and how to modify site output based on this data.

Chapter 9, Leveraging JavaScript, jQuery, and AJAX Scripts, makes plugin output very dynamic by using a number of popular script libraries.

Chapter 10, Adding New Widgets to the WordPress Library, shows how to add new widgets that users will be able to easily drag and drop to add content to their web pages.

Chapter 11, Fetching, Caching, and Regularly Updating External Site Data, explains how to extract data from external sites and locally cache that data for efficient use.

Chapter 12, Enabling Plugin Internationalization, prepares your plugin to be translated into any language to make it easier to be used by non-English speakers.

Chapter 13, Distributing Your Plugin on WordPress.org, shows you how to prepare your plugin for sharing with the global WordPress community.

To get the most out of this book

All code examples in this book have been tested against WordPress 5.9 using the Twenty Twenty-Two theme, unless otherwise noted. As WordPress always strives for backward compatibility, they will likely work with future versions as well. All other software tools needed are covered in Chapter 1, Preparing a Local Development Environment.

If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book's GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/WordPress-Plugin-Development-Cookbook-Third-Edition. If there's an update to the code, it will be updated in the GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots and diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781801810777_ColorImages.pdf

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "The widget method starts by calling the standard PHP extract function on the first parameter received, an array named $args, which contains a list of styling tidbits to render the widget."

A block of code is set as follows:

class Book_Reviews extends WP_Widget {

    function __construct () {

        parent::__construct( 'book_reviews',

            'Book Reviews',

            array( 'description' =>

                   'Displays list of recent book reviews' ) );

    }

}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

</tr><tr>

<td colspan="2">

<div class="g-recaptcha"

data-sitekey="[my-site-key]"></div>

</td>

Any command-line input or output is written as follows:

npm install --save-dev --save-exact @wordpress/scripts

Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: "Publish the new page and click on View Page to see the block on your development site."

Tips or Important Notes

Appear like this.

Sections

In this book, you will find several headings that appear frequently (Getting ready, How to do it..., How it works..., There's more..., and See also).

To give clear instructions on how to complete a recipe, use these sections as follows:

Getting ready

This section tells you what to expect in the recipe and describes how to set up any software or any preliminary settings required for the recipe.

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section usually consists of a detailed explanation of what happened in the previous section.

There's more…

This section consists of additional information about the recipe in order to make you more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Share Your Thoughts

Once you've read WordPress Plugin Development Cookbook, we'd love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we're delivering excellent quality content.

Chapter 1: Preparing a Local Development Environment

Before you start writing your first WordPress plugin, it is important to have a good set of tools in place that will allow you to work locally on your computer and be more efficient in your work. While it is possible to perform some development tasks with the built-in tools that are provided with the operating system, creating a solid local development environment will help you develop plugins quickly and have full control over your server settings to be able to test different configurations.

This chapter proposes a set of free tools that can easily be installed on your computer, regardless of your preferred operating system, to facilitate the development of your future WordPress plugins. These tools include a local web server to speed up page access and avoid sending files constantly to a remote server, a version control system to keep incremental backups of your work, and a code editor to enhance your editing capabilities.

We will cover the following recipes in this chapter:

Installing a local web server on your computerCreating a local version control repositoryInstalling a dedicated code editor/text editor

Technical requirements

You can find complete code examples on GitHub under the following repository: https://github.com/PacktPublishing/WordPress-Plugin-Development-Cookbook-Third-Edition.

Installing a local web server on your computer

The first step to preparing a local development environment is to install a local web server on your computer. This will transform your computer into a system capable of running the core WordPress code and performing all tasks related to rendering a WordPress website locally.

Having a local web server has many benefits:

It provides a quick response to the frequent page refreshes that are made as plugin code is written, tested, and refined, since all information is processed locally.It removes the need to constantly upload new plugin file versions to a remote web server to validate code changes.It allows development to take place when no internet connection is available (for example, when traveling on an airplane). This is only possible if your plugin code does not interact with external servers.It offers a worry-free programming environment where you cannot bring down a live website with a programming error or an infinite loop.

There are many free packages available online that contain all of the web server components necessary to run a WordPress installation.

How to do it…

Follow these steps to easily install the aptly named Local application from Flywheel:

Visit the Local website (https://www.localwp.com/) and download the appropriate package for your computer.

Note

Local is free and available for Windows, macOS, and Linux platforms. The screenshots and instructions in this recipe are based on Local version 6.1.5 running on Windows 11. The installation steps and exact dialog content may vary based on your choice of platform.

Launch the Local installer.On Windows, select whether the application should be available only to the user performing the application or to all users (requires administrator privileges), and then leave all the other options at their default values.Also on Windows, make sure that the Run Local checkbox is checked at the end of the installation process and click on Finish to exit the installer and start Local.

Figure 1.1 – Last page of the Local installation program on Windows

On macOS, open the installation package and drag the Local program to the Applications folder. Once this is done, search for Local and run it.When Local first starts, you will need to accept the application's Terms of Service and will also be given the option to activate Error Reporting to automatically report problems back to the Local team. You can activate the error reporting feature at your discretion.On the next screen, you will be prompted to create a free Local account. This is optional and can be bypassed by closing the account creation screen, bringing you to the main Local interface.

Figure 1.2 – Main Local interface

Click on + CREATE A NEW SITE to start the site creation process.Name your new site Plugin Development Site and click on CONTINUE.Select the Preferred option to create a site running the latest versions of PHP and MySQL, along with the nginx web server, and then click on CONTINUE.Specify a username, password, and email to create an account on your development WordPress site and then click on ADD SITE. The Local application will download and install the required components and start all of the required applications to have a working local WordPress installation. On Windows, you may need to allow multiple applications through the computer's firewall.

Figure 1.3 – Newly created local development site

Visit your local development site by clicking on the OPEN SITE button in the top-right corner of the Local interface. The default address of your site is http://plugin-development-site.local/.Back in the Local interface, click on the ADMIN button to visit your site's login page and connect using the credentials you provided during the site creation process.Make sure that the active theme is Twenty Twenty-Two. If not, install it and activate it.Still in the Local interface, click on the arrow next to the site path under the site name to access the site's local files on your computer. The WordPress software files will be found under the app\public directory within the site directory.

How it works…

The Local application contains all of the components necessary to run a web server capable of hosting a WordPress website on your computer. These components include:

nginx or the Apache web serverPHP interpreterMySQL database serverAdminer database management interface

Once we've created a development site with Local, the application registers a website domain that is recognized by the operating system as a request to communicate with the locally hosted development website. In this example, the domain created is http://plugin-development-site.local. When developing a local site that will eventually be deployed online, you can change the Site Domain field in the Local interface to match the domain of your target website. This allows you to work on the site locally while accessing it as if it was in its final online location.

There's more…

While Local is a full-featured local web server package and is available on the three major operating systems, there are many others available online. Most of these packages will run the required web services on the computer directly, while more advanced packages, such as Varying Vagrant Vagrants (VVV), will virtualize a complete Linux-based web server on your computer to create a more accurate replica of a final deployment environment optimized for WordPress. Here is a list of some of the most popular local web server packages:

For Windows:

WampServer (https://www.wampserver.com/en/)EasyPHP (https://www.easyphp.org/)

For macOS:

MAMP (https://www.mamp.info/en)

Cross-platform:

Varying Vagrant Vagrants (https://varyingvagrantvagrants.org)

Tip

For a more complete list of web server packages, visit https://en.wikipedia.org/wiki/List_of_AMP_packages.

Creating a remote web development environment

If it's not possible for you to set up a local web server to develop WordPress plugins, or if you are planning to share the development tasks with one or more developers, then an alternative to setting up a local web server is to create a remote development environment.

The easiest way to create such an environment, assuming that you already have a web hosting account set up, is to create a sub-domain off your main domain. This will allow you to create a standalone test installation for WordPress that will still provide safety from the point of view of affecting a live site but will not carry the other benefits of a local installation.

Creating a local version control repository

Version control is an important part of any code development project. Version control keeps track of a project's history, provides full and organized backups, and easily rolls back changes in order to get back to a known working state. Version control is also the best and most efficient way to share code and other files when developing a project in a team environment. In addition to being a great version control system that is easy to use and configure, Subversion (often referred to as SVN) is also the technology that manages all submissions on the official WordPress plugin directory. Therefore, by setting up and using a local Subversion repository during your initial plugin development, you will immediately be ready to share your creations with the community. We'll be covering the most commonly used Subversion commands in this recipe.

How to do it…

Follow these steps to create a local Subversion version control repository:

On Windows, visit the TortoiseSVN website (https://tortoisesvn.net/downloads.html) to download and install the free Subversion client for your version of Windows (32-bit or 64-bit).On macOS, you can download and install the Subversion binaries from Wandisco (https://www.wandisco.com/source-code-management/subversion#osx) or use Homebrew (https://brew.sh/) to easily add them to your computer.

Tip

While there are tools that offer a graphical user interface for Subversion, this recipe focuses on the creation of a local repository using Subversion's command-line tools to be more platform-agnostic.

Create a new folder on your hard drive that will host your local Subversion repository (for example, c:\WPSVN).Open a Command Prompt or Terminal and navigate to the newly created directory.Use the following command to create the required file structure in the target directory:

svnadmin create c:\WPSVN

Figure 1.4 – Creating a local Subversion repository with command-line tools

Use the cd command to navigate to the wp-content/plugins directory of your local WordPress installation, making sure to use double quotes around the path if it contains any spaces. For example, if you are using the Local software for your development site on a Windows computer, the command would be as follows, with ylefe replaced with your own user directory name:

cd "C:\Users\ylefe\Local Sites\plugin-development-site\app\public\wp-content\plugins"

Use the following command to import all files from the WordPress plugin folder into your local Subversion repository:

svn import -m "First import of complete WordPress plugin directory to repo." file:///c:/WPSVN

Enter the following command to check out all the files from the repository and force the local files to be overwritten:

svn checkout --force file:///c:/WPSVN .

Figure 1.5 – Importing and checking out all WordPress plugin files

Open the index.php file from your WordPress plugin directory in a text editor.Edit the comment on line 2 to change it from Silence is golden to Silence is everything, and then save and close the file.Create a new folder in the plugins directory named chapter1 using your computer's File Explorer/Finder or the directory creation command:

mkdir chapter1

Enter the following command from the Command Prompt or Terminal to add the new directory to the repository:

svn add chapter1

Navigate to the chapter1 directory using your computer's File Explorer or Finder and create a new text document named example.txt.Back in the Command Prompt or Terminal, use the following command to see the version control of the files contained in the plugin directory:

svn status

Figure 1.6 – Version control status for all files in the plugin directory

Note

As we can see from the output of the svn status command, the Subversion software correctly identified that the index.php file was modified (indicated by the letter M) and that the chapter1 folder is to be added to the repository (indicated by the letter A). However, it is unsure what to do with the example.txt file since we did not identify it with an svn command (indicated by a question mark). If we were to commit our changes to the repository at this time, the example.txt file would not be sent with the other changes.

Set the example.txt file to be added to the repository with the following command:

svn add chapter1\example.txt

Commit all changes to the local repository with the following command:

svn commit -m "Modified index.php, created a new directory and added a file in new directory"

The following figure shows the execution of the svn commit command and its output.

Figure 1.7 – Sending updates to the local Subversion repository

Delete the chapter1\example.txt file using your computer's File Explorer / Finder or with the appropriate command-line tool for your operating system (del on Windows and rm on macOS/Linux).Back in the Command Prompt or Terminal, run the svn status command to see that Subversion identifies the missing file with an exclamation mark.Use the following command to mark the file for deletion when the next commit command is executed:

svn delete chapter1\example.txt

Use the following command to delete the chapter1 directory and mark it for deletion in a single step:

svn delete chapter1

How it works…

Subversion is a free, open source version control system that is designed to keep file revisions organized and backed up over the course of a project's development, as well as provide access to older versions of all files at any time. If you have ever found yourself copying a directory on your computer and giving each copy sequentially numbered names, then you've already used a primitive version control system. Subversion and other version control tools are really just a more organized and efficient method of achieving the same goal of keeping backups of code files and being able to access any old version of a file.

While the default Subversion interface is a set of command-line utilities, TortoiseSVN and many other client applications provide graphical tools to create, access, and manage local and remote repositories.

In addition to familiarizing yourself with this system for later use on wordpress.org, using a local Subversion repository ensures that you always have easy access to older versions of your plugin files. This can be very useful in case a code change breaks your work and you cannot figure out how to get back to a working state.

Using the import Subversion command copies all the selected files to the repository. In addition to storing the files themselves, Subversion identifies each file with a revision number and an optional import message. The revision number is generated by Subversion and incremented every time a group of files is added. It is especially useful when searching through a repository's history.

Performing a checkout operation takes copies of all files from the repository and places them in the target directory. It also creates a .svn sub-directory that contains information on the address of the source repository, along with original versions of all the files that were checked out. These original files are used by Subversion to determine when changes have been made to any file relative to its contents when they were last committed, checked out, or updated. It might seem a bit redundant to have an original copy of all the files in the .svn folder when our repository is locally hosted. However, this is the same functionality that allows Subversion to identify file changes when working on a remote repository, even when your computer is not connected to the internet.

When the commit operation is performed, new files are added to the repository, modified files are uploaded and stored next to their previous versions, while deleted files are tagged as no longer being part of the current project version. While some of these behaviors might seem strange, it's by preserving previous versions of files and even keeping files that are no longer part of a project that Subversion is able to let us navigate through a project's entire history or bring back past versions of files.

There's more…

Using a Subversion client with a graphical user interface can greatly facilitate some of these tasks. For example, the version control status of files can be seen overlaid on top of the file and folder icons right in Windows File Explorer when TortoiseSVN (https://tortoisesvn.net/) is installed.

Figure 1.8 – TortoiseSVN integration in Windows File Explorer

GUI-based Subversion clients also include interactive menus for all of the commands covered in this chapter, but the actual steps to use them vary greatly from one client to the next. You should look for these graphical administration capabilities when searching for a Subversion client. For example, SmartSVN (https://smartsvn.com) offers free and paid versions of its client for Windows, macOS, and Linux, while Versions (https://versionsapp.com/) and Cornerstone (https://cornerstone.assembla.com/) are two popular paid applications on macOS.

Other version control systems

While Subversion is easy to learn and is the system that is used by WordPress on its official plugin repository, other version control systems, such as Git (https://git-scm.com/) and Mercurial (https://mercurial-scm.org/), are very popular in the open source development community and could also be considered to manage your plugin code. It's even possible to use a combination of version control systems with your code base. For example, you could use Subversion to commit to the official WordPress repository, but also use Git to commit the same code to a popular platform such as GitHub (https://github.com/), which makes it easy for your users to submit pull requests.

Viewing the differences in modified files

By using the svn diff <filename> command on any modified file, Subversion will bring up its built-in file difference viewer tool, highlighting the parts that are different between the last version of the file in the repository and the current version of this file. This allows users to see what changed at a glance and be sure that no code was modified inadvertently. It's also possible to display the results using a graphical diff tool, as long as the application command is in your system path, as shown in the following example:

svn diff index.php –-diff-cmd winmerge

Updating files to the latest repository version

If you are the only person committing files to a repository and you are working on a single computer, then you will never need to use the svn update command. This function is designed to compare your local files with the repository and check whether new files or new revisions are available in the repository that are not present locally. It will then apply all the necessary changes to the local versions of these files. Remember to use the svn update command regularly if you are working in a team environment or are developing a project across multiple computers.

Reverting uncommitted file changes

Until a file is committed to a repository, it's possible to reverse all the changes made to it since the last checkout, update, or committal by using the svn revert <filename> command. This can be useful if you made changes to the code that broke its functionality and want to get back to a known good state.

Viewing file history

As multiple versions of files are committed to a repository over time, Subversion keeps track of all the versions of these files along with the messages that were associated with each commit operation. The svn log <filename> command allows you to see a full history of changes made to one or more files.

Installing a dedicated code editor/text editor

Most operating systems provide a built-in text editor. While it is possible to create WordPress plugins using such a simple tool, it is highly recommended to install a dedicated code editor on your computer to simplify your plugin development work.

Getting ready

Of course, not all code editors are equal. Here are some of the features that you should look for when selecting a code editing application:

PHP syntax highlightingCompletion of PHP function namesAbility to search across multiple filesAbility to highlight all instances of search keyword(s) or selected textLine numberingAbility to resize the editor text or specify a replacement fontPossibility of opening multiple files simultaneously

The following editors contain most or all of these key features. Most are free tools, but some are paid applications.

Cross-platform:

Visual Studio Code (https://code.visualstudio.com)Sublime Text (https://www.sublimetext.com)

On Windows:

Notepad++ (https://notepad-plus-plus.org/)

On macOS:

TextMate (https://macromates.com)

On Linux:

Screem (http://www.screem.org/)

How to do it…

Follow these steps to install Visual Studio Code and learn about some of its core functions:

Visit the Vortex Studio Code site (https://code.visualstudio.com) and download the installation package for your platform of choice.Run the installation program for the editor and select the default settings.Launch the code editor.Connect to the administration section of your WordPress development site and click on the Plugins menu item.Check whether you have the Hello Dolly plugin from Matt Mullenweg installed. If not, go to the Add New section, search for it, and then click on Install Now.Back in the code editor, open the hello.php file from the plugins or plugins/hello-dolly directory of your local WordPress installation. You will see that different parts of the code are displayed in different colors based on the type of code.Double-click on a word to select it (for example, Hello). You will see any other instance of that same word highlighted across the file contents.Scroll down and hover your mouse cursor over the standard explode PHP function to see its definition and list of arguments.

Figure 1.9 – Visual Studio Code interface with PHP function data

How it works…

Code editors have built-in parsers that enable them to identify the parts of the code that are comments, PHP language functions, text strings, and a variety of other elements. Having these elements colored on the screen makes it much easier to read through code and to see that a function's name is not spelled correctly, or to quickly identify comments.

Another functionality that is crucial when developing plugins for WordPress is the ability to see line numbers in the editor. This function comes in handy, especially when PHP code errors come up, since the filename and line of code that was being processed at the time of the error are normally displayed. In most code editors, the developer can either scroll to the specific line or enter the line number in a quick Go To dialog box (Ctrl+G in Visual Studio Code) to jump to that line right away.

There's more…

Just like WordPress, Visual Studio Code has a rich plugin environment that allows its users to transform it into a complete development environment. The following extensions, all freely available from the built-in Marketplace, are highly recommended when developing WordPress plugins:

PHP Extension Pack by Felix Becker: Includes the PHP Debug extension to connect Visual Studio Code to an XDEBUG-enabled web server and be able to step through every line of code and set breakpoints to facilitate debugging. Also contains the PHP IntelliSense extension to augment the editor's autocompletion capabilities.SVN by Chris Johnson: Integrates Subversion version control functionality in the editor. As you modify the code, you'll be able to see modified lines in the editor margins. This extension will also identify all modified files and allow you to perform all interactions with your version control server right from the editor.WordPress Hooks Intellisense by John Billion: Adds the completion of WordPress API functions as you write your plugin code.

Chapter 2: Plugin Framework Basics

From its very first beginnings, WordPress has always been designed as a very open platform. This openness has been exemplified not only through its open source licensing and distribution model but also its open plugin architecture, providing developers with the ability to deliver an even richer experience to its users.

While a basic WordPress installation provides a great amount of functionality that continues to expand from one release to the next, users often need to add one or more features to make it the perfect website management system to bring their project to life. This is where plugins come into play. They can fill this gap by augmenting or manipulating virtually any aspect of a WordPress website's display and administrative tasks.

Just like WordPress, plugins are written in the PHP programming language, which is structurally similar to more traditional languages such as C and C++. This code is stored in plain ASCII text files that are read and executed on a web server when pages are requested to be displayed. The secret ingredient that enables plugins to have such great power in WordPress is the inclusion of callback mechanisms, called hooks, throughout the platform's source code. These hooks come in two flavors, called action and filter hooks, which allow plugins to add content to a site and modify data before it is displayed, respectively. Whether it's rendering a site's front page, a single article, or its administration pages, WordPress has thousands of entry points where custom functions can be executed.

Beyond their ability to augment WordPress functionality, a side benefit of plugins is that most functionalities they add to a site are independent of the active theme. Therefore, users who like to change their theme frequently don't have to worry about manually adding back custom elements to their new themes when they make a switch.

This chapter explains the difference between action and filter hooks and shows how to use them to write a first set of plugins that will range in functionality, from adding information to a page header to defining new custom shortcodes.

In this chapter, we will cover the following topics:

Creating a plugin file and headerAdding output content to page headers using plugin actionsUsing WordPress path utility functions to load external files and imagesModifying the site generator meta tag using plugin filtersAdding text after each item's content using plugin filtersInserting link tracking code in the page body using plugin filtersTroubleshooting coding errors and printing variable contentCreating a new simple shortcodeCreating a new shortcode with parametersCreating a new enclosing shortcodeLoading a style sheet to format plugin outputWriting plugins using object-oriented PHP

Technical requirements  

You can find complete code examples on GitHub in the following repository: https://github.com/PacktPublishing/WordPress-Plugin-Development-Cookbook-Third-Edition. 

Creating a plugin file and header

The first step of creating a plugin is to create a directory and a PHP file in the WordPress plugins directory and add the necessary information to have it recognized by the system. This first recipe shows you how to create a basic plugin file for WordPress and how to activate this new extension from the administration interface.

Getting ready

You should have access to a WordPress development environment, either on your local computer or a remote server, where you will be able to load your new plugin files (see Chapter 1, Preparing a Local Development Environment).

How to do it...

Follow these steps to create your first plugin header and activate the plugin in WordPress:

Navigate to the WordPress plugins directory (wp-content/plugins) of your development installation.Create a new subdirectory called ch2-plugin-header within the plugin directory.Navigate to this directory and create a new text file called ch2-plugin-header.php.Open the new file in a code editor and add the following code:

<?php

/*

Plugin Name: Chapter 2 - Plugin Header

Plugin URI:

Description: Declares a plugin that will be visible in

the WordPress admin interface

Version: 1.0

Author: Yannick Lefebvre

Author URI: http://ylefebvre.ca

License: GPLv2

*/

Note

While the Description text is shown on two separate lines in the code example, it should be entered as a single line in your code file to be completely displayed in the WordPress Plugins list.

Save and close the new file.Log in to the administration page of your development WordPress installation.Click on Plugins in the left-hand navigation menu to show a list of all installed plugins. You should see your new plugin listed next to the two default ones that come pre-packaged with WordPress:

Figure 2.1 – The WordPress Plugins page showing the newly created plugin

Note

The list of default plugins may vary depending on how you built your development environment. You will see Akismet and Hello Dolly if you installed WordPress manually but might not see them if you are running a local development tool such as Local.

Enable the plugin by clicking on the Activate link under its name. You will see that the background color of your new plugin changes to indicate that it has been activated, along with a message specifying that the activation was successful.

How it works...

Plugin files can either be located directly in the wp-content/plugins directory or in a subdirectory under this location, with most following this second approach. When you access the installed plugins list in the administration interface, WordPress scans the entire plugins directory, looking for PHP files that contain comments following the format specified in this recipe. In some cases, there can be more than one PHP file containing plugin header data in any of these directories, and each of them will show up as a separate entry in the Plugins list.

Taking a closer look at the code that we entered in the file, the first line of the plugin file (<?php) is a tag that identifies the beginning of the PHP code that will be analyzed and executed by the PHP interpreter. Optionally, we could include a closing PHP tag (?>) at the end of the file. However, most PHP developers omit the closing tag, since having any spaces after that tag will cause warnings to be displayed by the interpreter.

Tip

To ensure compatibility with most WordPress installations, it is important to use the complete <?php open tag syntax in your plugin code instead of the <? shorthand version. Not all PHP installations are configured to support the shorthand version, and many users don't have access to change this type of configuration on their server.

The second and last lines (/* and */) indicate that the text between these special delimiters should be considered as comments. Finally, each line within the comment contains a specific label, indicating the type of information that follows it. When this information is found, WordPress retrieves data about the plugin and adds it to the list.

When a plugin is activated, WordPress validates the file's content to be sure that it is valid PHP code. It will then execute this content every time any page is rendered on the site, whether that page is front-facing or a backend administration section. For this reason, it is preferable to activate plugins only when they are in use, to avoid site slowdowns.

Of course, at this point, our new plugin does not add or modify any functionality in our WordPress installation, since it does not contain any code, but this is still an important first step.

See also

The Installing a local web server on your computer recipe in Chapter 1, Preparing a Local Development Environment

Adding output content to page headers using plugin actions

A common action performed by plugins is to add extra content to