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 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 tracking code in the 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