WordPress Plugin Development Cookbook - Second Edition
eBook - ePub

WordPress Plugin Development Cookbook - Second Edition

Yannick Lefebvre

Share book
  1. 386 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

WordPress Plugin Development Cookbook - Second Edition

Yannick Lefebvre

Book details
Book preview
Table of contents
Citations

About This Book

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 examplesAbout 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 communityWho This Book Is ForIf 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 communityIn DetailWordPress 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 approachThis 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

Frequently asked questions

How do I cancel my subscription?
Simply head over to the account section in settings and click on “Cancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
Can/how do I download books?
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
What is the difference between the pricing plans?
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
What is Perlego?
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Do you support text-to-speech?
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Is WordPress Plugin Development Cookbook - Second Edition an online PDF/ePUB?
Yes, you can access WordPress Plugin Development Cookbook - Second Edition by Yannick Lefebvre in PDF and/or ePUB format, as well as other popular books in Computer Science & Programming in PHP. We have over one million books available in our catalogue for you to explore.

Information

Year
2017
ISBN
9781788299497
Edition
2

User Settings and Administration Pages

This chapter is focused on setting up pages that enable users to configure plugin settings. It covers the following topics:
  • Creating default user settings on plugin initialization
  • Storing user settings using arrays
  • Removing plugin data on deletion
  • Creating an administration page menu item in the settings menu
  • Creating a multi-level administration menu
  • Adding menu items leading to external pages
  • Hiding items that users should not access from the default menu
  • Rendering the admin page content using HTML
  • Processing and storing plugin configuration data
  • Displaying a confirmation message when options are saved
  • Adding custom help pages
  • Rendering the admin page contents using the Settings API
  • Accessing user settings from action and filter hooks
  • Formatting admin pages using meta boxes
  • Splitting admin code from the main plugin file to optimize site performance
  • Storing style sheet data in user settings
  • Managing multiple sets of user settings from a single admin page
  • Creating a network level plugin with admin pages

Introduction

As we saw in Chapter 2, Plugin Framework Basics, it is very easy for a plugin to register custom functions with action and filter hooks to change or augment the way WordPress renders web pages. That being said, some of the examples covered in Chapter 2, Plugin Framework Basics, have limitations when it comes to dealing with custom user information, such as the inability to easily specify a Google Analytics account number.
To make plugins easy to use for a wide audience, it is usually important to create one or more administration pages where users will be able to provide details that are specific to their installation, enter information on external accounts, and customize some of the aspects of the plugin's functionality. As an example, the Akismet plugin, provided in default WordPress installations, offers a configuration page that can be found under the Settings | Akismet configuration menu. Thankfully, WordPress has a rich set of functions that allows plugin developers to easily put together configuration pages that will seamlessly blend with the rest of the administrative panels.
This chapter covers how to use the WordPress Options Application Programming Interface (API) functions to store and access user options in the site database. It then goes on to explain how to create custom dialogs to provide users with complete control over the configuration of the plugins that you create.

Creating default user settings on plugin initialization

A typical first step of most user-configurable plugins is to create a default set of values for all options when the plugin is activated. These default options will subsequently be used to populate the plugin's settings page when it is visited by the site administrator. This recipe shows how to register a function that is called when a plugin is activated, and how to store option data in the site database.

How to do it...

  1. Navigate to the WordPress plugin directory of your development installation.
  2. Create a new directory called ch3-individual-options.
  3. Navigate to this directory and create a new text file called ch3-individual-options.php.
  4. Open the new file in a code editor and add an appropriate header at the top of the plugin file, naming the plugin Chapter 3 - Individual Options.
  5. Add the following line of code to register a function that will be executed when the plugin is activated, after its initial installation or following an upgrade:
register_activation_hook( __FILE__, 'ch3io_set_default_options' );
  1. Add the following code section to provide an implementation for the ch3io_set_default_options function:
function ch3io_set_default_options() {
if ( false === get_option( 'ch3io_ga_account_name' ) ) {
add_option( 'ch3io_ga_account_name', 'UA-0000000-0' );
}
}
  1. Save and close the plugin file. Execute the activation function that was just added by clicking on the Activate option of this chapter 3 - Individual Options plugin.
  2. In your web server's MySQL database administration tool, select your WordPress database (wordpressdev if you followed the recipe in Chapter 1, Preparing a Local Development Environment), then select the wpdev_options table. Click on the SQL tab, replace the default query with the following statement, and click on Go:
select * from wpdev_options where option_name = 'ch3io_ga_account_name'
  1. Your query should return a single row with the default value assigned to the new option:

How it works...

The register_activation_hook function is used to indicate to WordPress the name of the function that should be called when it activates the plugin. Unlike other hooks, this function requires the name of the main plugin code file to be sent as its first argument, along with the name of the associated function. To do this easily, we can leverage the PHP __FILE__ constant as the first argument, which will resolve to the filename.
When the callback function is called, we can use the Options API to create, update, or, delete settings in the options table of the site's MySQL database. In this specific example, we are using the add_option function to easily create an option called ch3io_ga_account_name with a default value of UA-0000000-0.
Just like function names, you should be careful when naming plugin options, to avoid conflicts with other plugins. A good practice is to add a unique prefix to the beginning of each variable name.
Before making a call to create the new option, the activation function checks whether the option is present in the WordPress options table using the get_option function. If the return value is false, indicating that the option was not found, a new default option can be created. Any other result would show that the plugin has been activated on the site previously and that options may have been changed from their default values. It is important to keep in mind when writing this code that plugins get deactivated and reactivated each time they are updated using the WordPress update tool, resulting in a call to their activation function. It is also possible that a user might have deactivated a plugin temporarily to debug site issues and brought it back at a later time, also resulting in the activation function being called.
Finally, it should be noted that it is possible to call the add_option function multiple times if more than one option is needed to implement a plugin's desired functionality. That being said, it is not necessary to verify the presence of all the options, as checking for a single one would indicate that they were all previously set.

There's more...

Beyond the creation of default values for a plugin, the activation hook can also be used to perform more advanced tasks, such as interacting with custom database tables or doing data initialization, as will be seen in later chapters. In contrast, the similar deactivation function hook does not have any real use within the creation of most plugins.

Deactivation function

Similar to the activation function that we used in this recipe, WordPress provides a way to register a deactivation function (using register_deactivation_hook). While it may be tempting to use this function to remove options created by the plugin, it is not possible to know why the activation function was ca...

Table of contents