Chapter 7. Plugin Settings

WHAT'S IN THIS CHAPTER?

  • Using a WordPress database to save and get data

  • Leveraging the API functions to write compact and future proof code

  • Saving global options, or per-user options

  • Saving special option types: expiring options

  • Creating a custom database table, when and how to do it

WordPress enables easy access to the database to store and retrieve data, such as options end users can modify and save in settings pages or internal information plugins you need to know. You learn how to save and fetch this data using internal WordPress functions and API.

THE OPTIONS API

The Options API is a set of functions that enable easy access to the database where WordPress, plugins, and themes save and fetch needed information.

Options are stored in a database table named, by default, wp_options and can be text, integers, arrays, or objects. For example, WordPress keeps in this table the title of your blog, the list of active plugins, the news articles displayed on the Dashboard, or the time when to check if a new version is available.

You'll now learn how to use the functions to access, update, and save options: add_option(), update_option(), get_option(), and delete_option().

Saving Options

You start by saving your first plugin option, which will be named boj_myplugin_color and have a value of red. The function call to do so is the following:

<?php
add_option( 'boj_myplugin_color', 'red' );
?>

The first parameter is your option name. It is crucial that you make it unique and self-explanatory. ...

Get Professional WordPress® Plugin Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.