WordPress Plugin Development Cookbook - Second Edition - Yannick Lefebvre - E-Book

WordPress Plugin Development Cookbook - Second Edition E-Book

Yannick Lefebvre

0,0
37,19 €

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

Mehr erfahren.
Beschreibung

Learn to create plugins for WordPress 4.x to deliver custom projects or share with the community through detailed step-by-step recipes and code examples

About This Book

  • Learn how to change and extend WordPress to perform virtually any task
  • Explore the plugin API through approachable examples and detailed explanations
  • Mold WordPress to your project's needs or transform it to benefit the entire community

Who This Book Is For

If you are a WordPress user, developer, or a site integrator with basic knowledge of PHP and an interest to create new plugins to address your personal needs, client needs, or share with the community, then this book is for you.

What You Will Learn

  • Discover how to register user callbacks with WordPress, forming the basis of plugin creation
  • Explore the creation of administration pages and adding new content management sections through custom post types and custom database tables
  • Improve your plugins by customizing the post and page editors, categories and user profiles, and creating visitor-facing forms
  • Make your pages dynamic using Javascript, AJAX and adding new widgets to the platform
  • Learn how to add support for plugin translation and distribute your work to the WordPress community

In Detail

WordPress is a popular, powerful, and open Content Management System. Learning how to extend its capabilities allows you to unleash its full potential, whether you're an administrator trying to find the right extension, a developer with a great idea to enhance the platform for the community, or a website developer working to fulfill a client's needs. This book shows readers how to navigate WordPress' vast set of API functions to create high-quality plugins with easy-to-configure administration interfaces.

With new recipes and materials updated for the latest versions of WordPress 4.x, this second edition teaches you 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 and execute custom user code. You will then see how to design administration panels, enhance the post editor with custom fields, store custom data, and modify site behavior based on the value of custom fields. You'll safely incorporate dynamic elements on web pages using scripting languages, 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.

Style and approach

This cookbook will take you through the creation of your first simple plugin to adding entirely new sections and widgets in the administration interface, so you can learn how to change and extend WordPress to perform virtually any task. Each topic is illustrated through realistic examples showing how to solve common problems, followed by detailed explanations of all concepts used

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 424

Veröffentlichungsjahr: 2017

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

Second Edition

 

 

 

Create powerful plugins to extend the world's most popular CMS

 

 

 

 

 

 

Yannick Lefebvre

 

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

WordPress Plugin Development Cookbook

Second Edition

 

Copyright © 2017 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, and its dealers and distributors will be held liable for any damages caused or alleged to be 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.

 

First published: July 2012

Second edition: July 2017

 

Production reference: 1140717

 

 

Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.

 

 

 

ISBN 978-1-78829-118-7

 

www.packtpub.com

Credits

Author

Yannick Lefebvre

Copy Editor

Akshada Lobo

Reviewers

Cyril Pierron

Ardian Yuli Setyanto

Project Coordinator

Ritika Manoj

Commissioning Editor

Smeet Thakkar

Proofreader

Safis Editing

Acquisition Editor

Shweta Pant

Indexer

Mariammal Chettiyar

Content Development Editor

Arun Nadar

Graphics

Jason Monteiro

Technical Editor

Ralph Rosario

Production Coordinator

Shantanu Zagade

About the Author

Yannick Lefebvre is a plugin developer who has published eight projects to the official WordPress repository. His first creation, Link Library, has been used on thousands of sites around the world. With a background in Computer Science and working for CM Labs Simulations a company providing software tools and simulators for vehicle and heavy equipment simulation he started writing plugins for his own WordPress site 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 WordPress plugin development services. You can find out more about him and his plugins on his website, Yannick's Corner.

I would like to thank the WordCamp Montreal organizers for giving me a chance to speak at multiple editions of the event, for creating great videos of the presentations, and 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 coming back to me to put together this second edition. Finally, I would like to thank my parents for always believing in me and encouraging me in all my projects.

About the Reviewers

Cyril Pierron is a tech-savvy, life-curious engineer. He started programming at the age of 8. He worked in the telecommunications industry for 13 years, leading network value added service application development. Since 2011 he has been working as an ecommerce solution architect, supporting customers and partners, building transactional sites on Salesforce Commerce Cloud platform. He is married and the father of a lovely 7-year old girl.

As an ecommerce expert, Cyril has witnessed over the past few years the convergence of content sites and online stores into one unified experience for the consumer. He has integrated with various content management platforms in the context of his projects.

I would like to thank Packt Publishing for giving me the opportunity to work on this book as a reviewer. I would also like to thank Yannick Lefebvre, who did a wonderful job writing it, and my wife, who showed quite a lot of patience and support as I kept working on this book after hours. Content management systems (CMS) are key for brands to share information and reach out to their communities and fans. WordPress is a reference in the CMS world, one of the best known systems in the market. This book will definitely help plugin developers quickly start building on it.

Ardian Yuli Setyanto, S.Kom, has played with programming since in high school. He joined national selection for Tim Olimpiade Komputer Indonesia (TOKI, Indonesia Computer Olympiad Team) in 2002 and 2003, which convinced him to study computer science at Gadjah Mada University (UGM), and he graduated in 2009 firstly among his other friends with a score 3.5/4.

He also used WordPress as his essay topic for bachelor degree, he developed his own plugin and combined it with a GSM phone to read and send SMS, instead of the usual email, to manage WordPress comments in his essay. After graduating from university, he start working as freelancer using WordPress and Prestashop. These CMS are widely used in his home country, Indonesia.

Now he is working as a backend developer using Symfony2, Rails, and Sinatra. You can reach him on Twitter: @ardianys.

I would like to thank Packt for giving me this wonderful opportunity as a reviewer on their book once again. I would like to thank Arun Nadar, who assisted me while I was reviewing Yannick's wonderful content. I would also like to thank my family, Niela, Nain, Nusa, and Mazaya. All praise to God.

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why subscribe?

Fully searchable across every book published by Packt

Copy and paste, print, and bookmark content

On demand and accessible via a web browser

Customer Feedback

Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1788291182.

If you'd like to join our team of regular reviewers, you can email us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!

To my wife, Andree, for her everlasting love, her patience throughout the writing process, and for being a great first proofreader. To my daughters, Evelyne and Gabrielle, for always making me smile, giving the best hugs in the world, and growing up to become wonderful young ladies.

Table of Contents

Preface

What this book covers

What you need for this book

Who this book is for

Conventions

Reader feedback

Customer support

Downloading the example code

Errata

Piracy

Questions

Preparing a Local Development Environment

Introduction

Installing a web server on your computer

How to do it...

How it works...

There's more...

Creating a remote web development environment

See also

Downloading and configuring a local WordPress installation

Getting ready

How to do it...

How it works...

Creating a local Subversion repository

How to do it...

How it works...

There's more...

Manual repository creation

Other version control systems

See also

Importing initial files to a local Subversion repository

Getting ready

How to do it...

How it works...

See also

Checking out files from a Subversion repository

Getting ready

How to do it...

How it works...

There's more...

Subversion file statuses

See also

Committing changes to a Subversion repository

Getting ready

How to do it...

How it works...

There's more...

Viewing the differences in modified files

Updating files to latest repository version

Reverting uncommitted file changes

Viewing file history

Installing a dedicated code editor/text editor

Getting ready

How to do it...

How it works...

Plugin Framework Basics

Introduction

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...

Action hooks online listings

Searching for hooks in the WordPress source code

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...

preg_replace function

Filter hooks online listings and the apply_filters function

See also

Adding text after each item's content using plugin filters

How to do it...

How it works...

There's more...

get_the_title and get_permalink functions

See also

Inserting link statistics tracking code in 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...

Built-in WordPress debugging features

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...

See also

User Settings and Administration Pages

Introduction

Creating default user settings on plugin initialization

How to do it...

How it works...

There's more...

Deactivation function

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...

Settings hook priority to determine menu order

See also

Creating a multi-level administration menu

How to do it...

How it works...

See also

Adding menu items leading to external pages

Getting ready

How to do it...

How it works...

See also

Hiding items which users should not access from the default menu

How to do it...

How it works...

Rendering the admin page contents using HTML

Getting ready

How to do it...

How it works...

There's more...

wp_nonce_field

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...

Rendering a drop-down list settings field

Rendering a text area settings field

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 network-level admin pages

Getting ready

How to do it...

How it works...

See also

The Power of Custom Post Types

Introduction

Creating a custom post type

Getting ready

How to do it...

How it works...

There's more...

Changing the custom post type permalinks slug

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

Displaying custom post type data in shortcodes

Getting ready

How to do it...

How it works...

There's more...

do_shortcode function

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 page title to include custom post data using plugin filters

Getting ready

How to do it...

How it works...

Customizing Post and Page Editors

Introduction

Capturing and displaying information using custom meta boxes

Getting ready

How to do it...

How it works...

There's more...

Adding a new meta box to all post types (including custom ones)

Displaying custom post data using filter functions

Getting ready

How to do it...

How it works...

See also

Hiding the Custom Field section in the post editor

Getting ready

How to do it...

How it works...

Extending the post editor to allow users to upload files directly

Getting ready

How to do it...

How it works...

See also

Accepting User Content Submissions

Introduction

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...

Moderating user-submitted content

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

Customizing User Data

Introduction

Adding custom fields to the user editor

Getting ready

How to do it...

How it works...

See also

Processing and storing user custom data

Getting ready

How to do it...

How it works...

See also

Displaying new user data in user list page

Getting ready

How to do it...

How it works...

See also

Using custom user data in containing shortcode

Getting ready

How to do it...

How it works...

See also

Creating Custom MySQL Database Tables

Introduction

Creating new database tables

Getting ready

How to do it...

How it works...

There's more...

Using phpMyAdmin to simplify code creation

Create tables in network installation

Deleting custom tables on plugin removal

Getting ready

How to do it...

How it works...

See also

Updating custom table structure on plugin upgrade

Getting ready

How to do it...

How it works...

See also

Displaying custom table data on an admin page

Getting ready

How to do it...

How it works...

See also

Inserting and updating records in custom tables

Getting ready

How to do it...

How it works...

See also

Deleting records from custom tables

Getting ready

How to do it...

How it works...

See also

Displaying custom database table data in shortcodes

Getting ready

How to do it...

How it works...

See also

Implementing a search function to retrieve custom table data

Getting ready

How to do it...

How it works...

See also

Importing data from a user file into custom tables

Getting ready

How to do it...

How it works...

See also

Leveraging JavaScript, jQuery, and AJAX Scripts

Introduction

Safely loading jQuery onto WordPress web pages

Getting ready

How to do it...

How it works...

There's more...

jQuery noconflict mode

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

Getting ready

How to do it...

How it works...

There's more...

Removing the dialog close button

Displaying pop-up dialogs on select pages

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

Adding New Widgets to the WordPress Library

Introduction

Creating a new widget in WordPress

Getting ready

How to do it...

How it works...

There's more...

Plugins extending other plugins

See also

Displaying configuration options

Getting ready

How to do it...

How it works...

See also

Validating configuration options

Getting ready

How to do it...

How it works...

See also

Implementing the widget display function

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

Enabling Plugin Internationalization

Introduction

Changing the WordPress 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...

Translation template file

See also

Loading a language file in the plugin initialization

Getting ready

How to do it...

How it works...

There's more...

Updating a translation file

Advanced translation functions

Localizing JavaScript files

See also

Distributing Your Plugin on wordpress.org

Introduction

Creating a README file for your plugin

Getting ready

How to do it...

How it works...

There's more...

Releasing specific plugin versions using tags

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...

Checking out plugins to your development installation

See also

Providing plugin banner and thumbnail images

Getting ready

How to do it...

How it works...

See also

Preface

Developing plugins for WordPress is the next big thing for you if you are an administrator looking to enhance a personal site with custom functionality for which no plugin exists, a developer looking to enhance the WordPress platform with new ideas for the community, or a website designer building a specific project for a client. Learning how to create WordPress plugins will allow you to unleash the full potential of the most popular web content management system.

As an early WordPress adopter, before version 1.0 was out, I started building plugins to add functionality to my personal site. Once I got these new elements in place, I quickly realized that other users could benefit from these extensions, and started distributing them online. To this day, I always love hearing back from users of my creations and finding out how they have put them to use and what new functionality they think would make them even better.

While developing plugins might initially sound a little bit like black magic, this book shows you how easy creating plugins actually is through a series of step-by-step recipes. If you have previously added code to a theme's functions file, you may even be familiar with some of the mechanics explained in this book. With all of the information contained in this book, you will quickly be able to create your own plugins or dissect existing ones to add that extra bit of missing functionality that you require. Before you know, you'll be publishing your own creations to the official WordPress plugin repository!

Let's start learning how to cook up great WordPress plugins!

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, Accepting User Content Submissions, allows users to submit their own content to new content sections that will be managed by your plugins.

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

Chapter 8, Creating Custom MySQL Database Tables, leverages the power of MySQL to create custom database tables in a site database to store and retrieve custom 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, indicates how to add new widgets that users will be able to easily drag and drop to add content to their web pages.

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

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

What you need for this book

Chapter 1, Preparing a Local Development Environment, walks you through all of the tools that are useful to have when developing plugins for WordPress, including a local web server, a Subversion client, and a dedicated code editor. While this book will always describe all of the steps necessary to perform its recipes, having a good understanding of WordPress will allow you to fully appreciate the information contained in these pages.

Who this book is for

This book is for WordPress users, developers, or site integrators with basic knowledge of WordPress and PHP and an interest in creating new plugins to address their personal needs, client needs, or share new ideas with the WordPress community.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "create a text file called uninstall.php in the ch8-bug-tracker directory and open it in a code editor."

A block of code is set as follows:

add_filter( 'the_generator', 'ch2gf_generator_filter', 10, 2 );

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

echo '<tr style="background: #FFF">';

echo '<td><input type="checkbox" name="bugs[]" value="';

echo intval( $bug_item['bug_id'] ) . '" /></td>';

echo '<td>' . $bug_item['bug_id'] . '</td>';

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Here, we added an inner grid with two full-size columns; one for thePriceof an item and the other will wrap up theQuantitycomponent."

Warnings or important notes appear in a box like this.
Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply email [email protected], and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your email address and password.

Hover the mouse pointer on the

SUPPORT

tab at the top.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box.

Select the book for which you're looking to download the code files.

Choose from the drop-down menu where you purchased this book from.

Click on

Code Download

.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for Windows

Zipeg / iZip / UnRarX for Mac

7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/WordPress-Plugin-Development-Cookbook-Second-Edition. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

Preparing a Local Development Environment

We will cover the following topics in this chapter:

Installing a web server on your computer

Downloading and configuring a local WordPress installation

Creating a local Subversion repository

Importing initial files to a local Subversion repository

Checking out files from a Subversion repository

Committing changes to a Subversion repository

Installing a dedicated code/text editor

Introduction

Before we start writing our 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. In addition to installing and learning how to use these tools, this chapter also shows how to download and configure a local WordPress installation on a local web server.

Installing a web server on your computer

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

Having a local web server has many benefits, as follows:

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)

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. This recipe shows you how to easily install one of these packages.

How to do it...

Visit the XAMPP website (

https://www.apachefriends.org/

) and download the appropriate XAMPP package for your computer.

XAMPP is available for Windows, macOS, and Linux platforms. The screenshots in this recipe were taken from XAMPP version 5.6.30 on Windows 10. The installation steps and exact dialog content might vary based on your choice of platform.

Optional on Windows: Disable the Windows

User Access Control (UAC)

feature to give full permissions to XAMPP to install itself on your system (look up the steps to perform this procedure on your favorite search engine).

Launch the XAMPP installer (

xampp-win32-5.6.30-0-VC11-installer.exe

on the Windows platform).

Acknowledge the warning message about

User Access Control

(

UAC

) and click on

Next

to start the installation process.

On the following screen, which lists all of the components that can be installed, uncheck the boxes for

FileZilla FTP Server

,

Mercury Mail Server

,

Tomcat

,

Perl

, and

Webalizer

, then click on

Next

:

On the

Installation folder

screen, leave the default value for the installation directory if possible (

c:\xampp

), since some references to this folder will be made in this book, then click on

Next

.

Click on the

Next

button to proceed with the web server installation.

Make sure that the option to start the

Control Panel

is checked and click on

Finish

once the installation is complete.

Select your preferred language for the

XAMPP Control Panel

and click on

Save

to launch the application.

Click the

Start

buttons for

Apache

and

MySQL

to launch these modules. Their names will be highlighted in green once they have been successfully started, as shown in the following screenshot:

Open a web browser and navigate to the address

http://localhost

to display your local web server's welcome page:

Open the

c:\xampp\apache\conf\httpd.conf

file in a text editor (for example, Notepad).

Search for the

DocumentRoot

configuration option and change its value to a different location on the disk to avoid keeping your project files under the original installation directory. For example, you could set it to a new directory designed to hold your local development installation of WordPress, such as

DocumentRoot "C:/WPDev"

.

Notice that forward slashes are used in this path. You should be careful if you copy and paste a path from a file explorer window.

Search for the

Directory

option and change it to the same path that was used for

DocumentRoot

, that is,

<Directory "C:/WPDev">

.

Save and close the

httpd.conf

file.

Create the directory specified as

DocumentRoot

, if it does not already exist on your computer.

Open

XAMPP Control Panel

.

Stop and re-start the

Apache

service for the new configuration to take effect.

Trying to access the local web server's welcome page will no longer work after having performed steps 14 through 20, since the new directory specified is currently empty. This will be corrected in the next recipe.

How it works...

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

Apache web server

PHP interpreter

MySQL database server

phpMyAdmin database management interface

The XAMPP package also includes other components, which are not required to run a local WordPress development site.

Once XAMPP is installed and started, the keyword localhost that we type in the web browser is recognized by the operating system as a request to communicate with the web server on the local computer and the Apache web server displays the welcome page from its documentation.

The XAMPP documentation is a set of flat HTML files located in the c:\xampp\htdocs directory on the Windows platform. This is the web server's default working directory.

The last few steps of the recipe instruct the Apache web server to look for the local website's content in a new directory. This is a safety precaution to be sure that site files are not deleted inadvertently if XAMPP is uninstalled. It can also help in managing multiple sites on a single computer.

There's more...

While XAMPP 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 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 (

http://www.wampserver.com/en/

)

EasyPHP (

http://www.easyphp.org/

)

For macOS X:

MAMP (

https://www.mamp.info/en

)

For Windows, Mac, or Linux:

Varying Vagrant Vagrants (

https://varyingvagrantvagrants.org

)

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 people, 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 affecting a live site, but will not carry the other benefits of a local installation.

See also

The

Downloading and configuring a local WordPress installation

recipe

Downloading and configuring a local WordPress installation

The next component of our local development environment is to install WordPress on your local web server to run a fully working website and have all of its files hosted locally.

WordPress has always prided itself with its easy five minutes installation process. Installing it on a local web server is even easier and quicker than it would be on a live remote server. This recipe covers the creation of a MySQL database to store all data related to our new WordPress installation and the actual setup process.

Getting ready

This recipe assumes that you have a local web server installed on your computer. This web server can be a fresh install performed using the previous recipe or can be from a previous installation. The steps in the following section are written with a focus on new local web servers. If you have created a new account to access the MySQL database or changed the root user's password, some of the steps will change slightly. The location of the phpMyAdmin tool might also be different if you are using a different web server than XAMPP. You should refer to your web server's documentation to find out what that address is.

How to do it...

In the web browser, navigate to the address

http://localhost/phpmyadmin/

to access your web server's database administration tool.

Click on

Databases

tab in

phpMyAdmin

.

Type the name of the new database to be created in the empty field following to the words

Create database

. In this case, we will use the name

wordpressdev

:

Click on the

Create

button to complete the database creation process.

Download the latest WordPress installation package from the official WordPress website (

https://wordpress.org

)

. The download link can be found on the very first page of the website and the download package will work on any web server, local, or remote.

The following instructions have been tested against WordPress version 4.8. While the installation process does not usually change much between versions, there may be slight differences in these steps on newer versions.

Extract the WordPress archive file contents using your favorite file archiver utility or your operating system's built-in capabilities.

 

Copy the contents of the resulting

wordpress

folder to your local web server's web content directory (

c:\WPDev

, if you followed the previous recipe). You should not copy the

wordpress

folder itself unless you want the address of your WordPress website to be

http://localhost/wordpress

.

Direct your web browser to

http://localhost

to start the WordPress installation process.

Select your preferred language and click on

Continue

.

On the next page, click on the

Let's Go

button to start your development site's configuration.

Update the

Database Name

field to reflect the name of our newly-created database (

wordpressdev

).

Set the MySQL

User Name

to

root

.

Delete all the characters from MySQL

Password

to leave it empty, since local MySQL server root accounts are typically configured without any password.

Leave the

Database Host

field with its default value (

localhost

).

Change the

Table Prefix

field from its default value to

wpdev_

:

Click on the

Submit

button to validate the information entered. If any parameters are not entered correctly, or if the WordPress installation process cannot correctly access your database server, it will display an error page and give you an opportunity to make corrections.

Click on the

Run the install

button for WordPress to create the required table structure in the designated MySQL database.

Specify a

Site Title

(for example,

Development Site

).

Set

Username

for the admin user. For increased security, it's always best to choose a username that people would not be able to easily guess. Obvious names such as admin or administrator should be avoided.

Optionally, change the randomly generated password with a password of your own choice. If WordPress determines that your new password is weak, you will need to check the additional checkbox that appears to confirm that you want to use a weak password.

Enter your email address in the appropriate field (although no email will actually be sent on most local development installations).

If you are configuring a live external development server, check the

Discourage search engines from indexing this site

option, since we do not want this development site to appear anywhere.

Click on

Install WordPress

to complete the installation and you will be automatically logged in to the site's WordPress

Dashboard

.

 

Click on the

Development Site

link in the Dashboard admin bar to see your new site:

How it works...

In the first few steps, the phpMyAdmin interface is used to create a database on the local MySQL server. This web-based database management tool comes bundled with XAMPP and most other web servers. The http://localhost/phpmyadmin address will always take you to the database administration tool, even if you relocate your web server's document root directory as documented in the previous recipe.

Once a database is created and the WordPress files have been copied to the correct location, pointing your browser to the local web server gets it to search through the document root directory to find HTML files to send back to the browser or PHP files to execute. In the case of WordPress, the web server finds the index.php file and executes it using its PHP interpreter. As the WordPress code is executed, it checks if a configuration file is present and launches the installation process when it does not find one. The WordPress code does not see any difference between the local web server that we are running it on and a remote live web server that would be accessible anywhere online.

While we specified an email address for the administrator during the installation, many local web servers are not configured to send out email messages so we will never receive any email communication in these cases. It is preferable to use a remote server when developing and testing email functionality in a plugin.

Once this recipe has been completed, you will have a functional WordPress installation in place.

Creating a local Subversion repository

Version control is an important part of any code development project, to keep track of a project's history, to have full and organized backups, and to be able to easily roll back changes 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.

How to do it...

Visit the

TortoiseSVN

website (

https://tortoisesvn.net/downloads.html

) and download the free Subversion client for your version of Windows (32-bit or 64-bit).

While this recipe focuses on the creation of a local repository on the Windows platform, equivalent tools for other platforms are discussed after the recipe steps, in the There's more... section.

Launch the TortoiseSVN installation program and install it using all the default installation options.

Create a new folder on your hard drive that will host the local Subversion repository (for example,

c:\WPSVN

).

Right-click on the new folder and select the

TortoiseSVN | Create repository here

menu item, then click on

Start Repobrowser

. TortoiseSVN will create the required file structure in the target directory and display the contents of the repository, which is currently empty:

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 or adding dates to their names, then you will recognize that version control is really just a more organized and efficient method of achieving the same goal of keeping backups of known working versions of code files and being able to access any older 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 will ensure that you will always have older versions of your plugins easily accessible in case a code change that you perform breaks your work and you cannot figure out how to get back to a working state.

There's more...

While there are many Subversion clients available online to interact with a repository, not all of them include the necessary administration tools to easily create a repository, as shown in this recipe. You should look for these administration capabilities when searching for a Subversion client for non-Windows platforms.

On macOS X, versions (http://versionsapp.com/) and Cornerstone (https://www.zennaware.com/cornerstone) offer similar capabilities but are paid applications.

On Linux, PagaVCS is a free TortoiseSVN clone (https://code.google.com/p/pagavcs/) while SmartSVN (http://smartsvn.com) is a paid SVN client.

Manual repository creation

If your Subversion client does not offer the ability to create a local repository, you can download the Subversion command-line tools from the official Subversion website (https://subversion.apache.org/packages.html) and create a repository manually following instructions found in the online Subversion reference manual (http://svnbook.red-bean.com/).

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 gaining traction in the open source development community and could also be considered to manage your plugin code.

See also

The

Importing initial files to a local Subversion repository

recipe

Importing initial files to a local Subversion repository

Once you have a local repository in place, this recipe describes the steps required to add files and start tracking their revisions over time. To have the flexibility to create multiple plugins, as discussed throughout this cookbook, without having to worry about adding each of them to the repository individually, we will add the entire WordPress plugin directory to your local repository.

Getting ready

You should have already installed a Subversion client on your computer and created a local repository, as described in the Creating a local Subversion repository recipe. These steps will be slightly different based on the Subversion client that you have selected and your operating system.

How to do it...

Navigate to the

wp-content/plugins

directory of your local WordPress installation (for example,

c:\WPDev\wp-content\plugins

, if you followed the previous recipe) with the file explorer.

Right-click on the folder and select the

TortoiseSVN | Import

menu item.

Enter the file location of your local Subversion repository in the