Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
WordPress Plugin Development Cookbook
WordPress Plugin Development Cookbook

WordPress Plugin Development Cookbook: Create powerful plugins to extend the world's most popular CMS , Second Edition

eBook
$24.99 $35.99
Paperback
$43.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

WordPress Plugin Development Cookbook

Plugin Framework Basics

In this chapter, we will cover the following topics:

  • Creating a plugin file and header
  • Adding output content to page headers using plugin actions
  • Using WordPress path utility functions to load external files and images
  • Modifying the site generator meta tag using plugin filters
  • Adding text after each item's content using plugin filters
  • Inserting link statistics tracking code in page body using plugin filters
  • Troubleshooting coding errors and printing variable content
  • Creating a new simple shortcode
  • Creating a new shortcode with parameters
  • Creating a new enclosing shortcode
  • Loading a style sheet to format plugin output
  • Writing plugins using object-oriented PHP

Introduction

From its very first versions, 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 have the need to add one more feature to make it the perfect website management system. This is where the 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...

Creating a plugin file and header

The first step of creating a WordPress plugin is to create a PHP file inside of the 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 see and 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.

How to do it...

  1. Navigate to...

Adding output content to page headers using plugin actions

A common action performed by plugins is to add extra content to the header of visitor-facing pages generated by WordPress. This recipe shows you how to register an action hook function to be able to add such additional content. To make this example more concrete, we will use the Google Analytics page header JavaScript code that so many people use to get good page view statistics for their site.

How to do it...

  1. Navigate to the WordPress plugin directory of your development installation.
  2. Create a new directory called ch2-page-header-output.
  3. Navigate to this directory and create a new text file called ch2-page-header-output.php.
  4. Open the new file in a code editor and...

Using WordPress path utility functions to load external files and images

On occasion, plugins need to refer to external files (for example, images, JavaScript, or jQuery script files) that are stored in the plugin directory. Since users are free to rename a plugin's folder or even install plugin files straight into the WordPress plugin directory, paths to any external files must be built dynamically based on the actual plugin location. Thankfully, a number of utility functions are present to simplify this task. In this recipe, we will write a simple plugin that will add a favicon meta tag to a website's header, pointing to an image file located in the plugin directory.

How to do it...

  1. Navigate to the WordPress plugin...

Modifying the site generator meta tag using plugin filters

Beyond adding functionality or content to a site, the other major task commonly performed by plugins is to augment, modify, or reduce information before it is displayed on the screen. This is done by using WordPress filter hooks, which allow plugins to register a custom function through the WordPress API to be called, since content is prepared before it is sent to the browser. In this recipe, you will learn how to implement your first filter callback function to modify the contents of the generator meta tag that is output as part of the site header.

How to do it...

  1. Navigate to the WordPress plugin directory of your development installation.
  2. Create a new directory...

Adding text after each item's content using plugin filters

After making a number of changes to the page header, the generator meta tag, and the site favicon, this recipe takes a more active role by adding a link to each post or page, allowing visitors to email a link to the item that they are currently viewing. This functionality is implemented using a filter hook attached to the page and post content, allowing our custom function to append custom output code to all entries that get displayed on the screen.

How to do it...

  1. Navigate to the WordPress plugin directory of your development installation.
  2. Create a new directory called ch2-email-page-link.
  3. Navigate to this directory and create a new text file called ch2-email...

Inserting link statistics tracking code in page body using plugin filters

After creating two filter functions that append text to the existing content, this recipe shows you how to modify the page content before it is displayed on the screen. More specifically, the following plugin will expand on the Google Analytics header plugin created earlier and add a JavaScript function to all the links that are included in posts and pages to track when they are clicked by visitors.

Getting ready

You should have already followed the Adding output content to page headers using plugin actions recipe to have a starting point for this recipe and the resulting plugin should be active in your development site. Alternatively, you can download...

Troubleshooting coding errors and printing variable content

As you transcribe code segments from the pages of this book or start writing your own plugins, there is a strong chance that you will have to troubleshoot problems with your code or have trouble working with data that your plugin is meant to manipulate. This recipe shows the basic techniques to identify and quickly resolve these errors while creating a plugin that will hide an item from the navigation menu for users who are not logged in to your site.

How to do it...

  1. Navigate to the WordPress plugin directory of your development installation.
  2. Create a new directory called ch2-nav-menu-filter.
  3. Navigate to this directory and create a new text file called ch2-nav-menu...

Creating a new simple shortcode

Shortcodes are a very popular tool in WordPress that allow users to easily add content generated by plugins or themes to any page or post without needing to be familiar with PHP code and editing theme template files. As they are very simple to create, shortcodes can also be used to easily automate the output of content that repeatedly needs to be included in your site's content.

This recipe explains how to create a new custom shortcode that will be used to quickly add a link to a Twitter page in any post or page, automating a repetitive task.

How to do it...

  1. Navigate to the WordPress plugin directory of your development installation.
  2. Create a new directory called ch2-twitter-shortcode...

Creating a new shortcode with parameters

While simple shortcodes already provide a lot of potential to output complex content to a page by entering a few characters in the post editor, shortcodes become even more useful when they are coupled with parameters that will be passed to their associated processing function. Using this technique, it becomes very easy to create a shortcode that accelerates the insertion of external content in WordPress posts or pages by only needing to specify the shortcode and the unique identifier of the source element to be displayed.

We will illustrate this concept in this recipe by creating a shortcode that will be used to quickly add Twitter feeds to posts or pages.

How to do it...

  1. Navigate...

Creating a new enclosing shortcode

A different type of shortcode is available in WordPress that encloses content in posts and pages. Using a syntax similar to HTML tags, enclosing shortcodes can be used to identify parts of an item's content that need to be treated in a special way. For example, it is possible to use this type of shortcode to style a part of the post.

As an example of how to create enclosing shortcodes, this recipe shows you how to create a set of tags that will identify part of a post or page that should only be shown to visitors that are logged in to a site. In this way, the shortcode acts similarly to a filter hook, with the added bonus that you do not need to parse for instances of these tags, as would normally be done in a filter.

How to do it...

...

Loading a style sheet to format plugin output

When a plugin adds custom content or inserts styling tags to a post or page's existing content, as was done in the previous recipe showing how to create an enclosing shortcode, it usually needs to load a custom style sheet to style these new elements. This recipe shows how to add a style sheet in the WordPress style queue to format the private output created in the previous recipe. This queue is processed when the page header is rendered, listing all the style sheets that need to be loaded to display the site correctly.

Getting ready

You should have already followed the Creating a new enclosing shortcode recipe to have a starting point for this recipe and the resulting plugin...

Writing plugins using object-oriented PHP

So far, all plugin examples that have been covered in this chapter have been written using the procedural PHP programming style, with all the functions declared directly in the main body of the plugin and the hook registration functions having direct access to these functions.

WordPress can also be written using an object-oriented PHP approach. This recipe explains how to convert the code from the previous recipe into a class-based version of the same functionality.

Getting ready

You should have already followed the Loading a style sheet to format plugin output recipe to have a starting point for this recipe. Alternatively, you can download the resulting code (Chapter 2/ch2-private...

Left arrow icon Right arrow icon

Key benefits

  • 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

Description

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.

Who is this book 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
Estimated delivery fee Deliver to Egypt

Standard delivery 10 - 13 business days

$12.95

Premium delivery 3 - 6 business days

$34.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 26, 2017
Length: 386 pages
Edition : 2nd
Language : English
ISBN-13 : 9781788291187
Vendor :
WordPress Foundation
Languages :
Concepts :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Egypt

Standard delivery 10 - 13 business days

$12.95

Premium delivery 3 - 6 business days

$34.95
(Includes tracking information)

Product Details

Publication date : Jul 26, 2017
Length: 386 pages
Edition : 2nd
Language : English
ISBN-13 : 9781788291187
Vendor :
WordPress Foundation
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 141.97
WordPress Plugin Development Cookbook
$43.99
WordPress Complete, Sixth Edition
$48.99
Wordpress Web Application  Development
$48.99
Total $ 141.97 Stars icon
Banner background image

Table of Contents

12 Chapters
Preparing a Local Development Environment Chevron down icon Chevron up icon
Plugin Framework Basics Chevron down icon Chevron up icon
User Settings and Administration Pages Chevron down icon Chevron up icon
The Power of Custom Post Types Chevron down icon Chevron up icon
Customizing Post and Page Editors Chevron down icon Chevron up icon
Accepting User Content Submissions Chevron down icon Chevron up icon
Customizing User Data Chevron down icon Chevron up icon
Creating Custom MySQL Database Tables Chevron down icon Chevron up icon
Leveraging JavaScript, jQuery, and AJAX Scripts Chevron down icon Chevron up icon
Adding New Widgets to the WordPress Library Chevron down icon Chevron up icon
Enabling Plugin Internationalization Chevron down icon Chevron up icon
Distributing Your Plugin on wordpress.org Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.4
(12 Ratings)
5 star 58.3%
4 star 33.3%
3 star 0%
2 star 8.3%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Toddd L. Tomlinson Sep 25, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The switch from Drupal to Wordpress has been fairly painless thanks to this book! I was off and running and building plugins on the first day of my Wordpress adventures. A great book with just the right information in the right format.
Amazon Verified review Amazon
patrick kellogg Aug 10, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is super. It is packed with info and from it I quickly wrote a certificate tracker for LearnDash LMS based on the bug tracker. The author explains everything in detail and the code is organized properly so its a snap to activate the next plugin in the series as you ramp up. Highly recommended.
Amazon Verified review Amazon
Maxime Jobin May 04, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I usually never use books/ebooks when reading about software development. I have to admit that the way the book is structured and how easy the examples are built makes it a "reference book" I really enjoyed. I loved how many examples there is and the fact they are linked to practical use cases. Any developer that starts developing plugins for WordPress should buy it.
Amazon Verified review Amazon
Bruno P. Aug 10, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
good seller, good product
Amazon Verified review Amazon
Mark Mar 14, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is for developers who know at least some PHP. After my company abruptly decided to switch to Wordpress for their news site this book gave me a quick ramp up to be able to show I know something about plugins quickly. It's a good intro for developers to WordPress Plugins by showing some real-world examples.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact [email protected] with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at [email protected] using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on [email protected] with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on [email protected] within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on [email protected] who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on [email protected] within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela