Mastering the WordPress Options API

WordPress Options header

Note: We’ve revised and expanded this article on the WordPress Options API as part of Up and Running, our multimedia guide to the principles of WordPress development.

If you’d like the exact text of the chapter from the Up and Running e-book—including Key Takeaways, a Summary Limerick (!), and a Quiz to test your knowledge—here’s a PDF download: Mastering the WordPress Options API (PDF).

And if you like the chapter (here or in PDF form), you’ll love Up and Running, which is 300+ pages and 100+ tutorial videos of WordPress education at the same level of quality. 🙂

Enjoy learning the WordPress Options API!

WordPress developers commonly need to record and change small pieces of sitewide data. These pieces of data are known as site options (or, sometimes, “site settings”). Examples could include:

  1. Retrieve the URL of the site’s custom header logo
  2. Set a custom background color across the site
  3. Programmatically update the email address of the site’s main administrator

Beyond these few examples, you’ll probably find browsing your wp_options table fascinating. (As a note, the wp_ prefix can change based on site configuration, but the options part won’t.)

So many things are recorded as site options:

WordPress Options API Options database table

Click to enlarge

This page captures many of the options you set on a new WordPress site (and can change in Settings > General in the WordPress admin menu). For example, blogname | WPShout gives the overall title for the site itself, and start_of_week | 1 means that the site’s week starts on Monday.

In this chapter, we’ll be walking through how to access, add, change, and remove site options.

How to Work with Site Options: the WordPress Options API

The Options API is lovably simple.

The Options API bears a strong resemblance to WordPress custom fields. Custom fields let you store discrete post-level data, whereas the Options API lets you store little bits of sitewide data. Other than that, they operate pretty similarly!

All site options are essentially name/value pairs: the name of the option, and the value that the option should be assigned. You can access, add or change, and delete these options with three easy-to-use functions:

  1. get_option()
  2. update_option()
  3. delete_option()

We’ll examine each of these functions, and get into a couple of examples.

get_option()

The Options API is lovably simple, and nowhere more so than get_option(). Here’s how to access our blogname option—the formal title we’ve set for the site:

<?php get_option( 'blogname' ); ?>

That’s it! Only a couple of footnotes to add to this very simple picture.

If the Option Doesn’t Exist

By default, if you ask for an option that hasn’t been set, get_option() will return false. If you want something other than false, you can pass in a second value to get_option(), specifying what you want back if the option doesn’t exist. We don’t use this option most of the time, so we’re not dwelling on it.

When the Option is a Complex Data Type

If our option was a PHP object or array when set, that’s what we get back from get_option(): the full-fledged PHP object or array. So get_option() isn’t confined to strings, and you don’t have to worry about any manual unserialize()-type work that you might be considering if you come from a general PHP background.

update_option()

Both creating and updating an option uses update_option(), as follows:

<?php update_option( 'blogname', 'Up and Running' ); ?>

update_option() updates an option’s value. If the option doesn’t already exist, it creates the option with the specified value. It returns true if the option was changed, and false if the option was not changed from its prior value, or if the attempt to update the option failed.

update_option()Function Arguments

update_option() takes two arguments:

  1. The name of the option
  2. The value the option is to take

As with custom fields, there is an add_ function, add_option(), that we recommend you ignore. update_option() behaves more predictably in both adding and updating options.

Since WordPress version 4.2.0, the function also takes a third argument, $autoload. We’d recommend you ignore this option as well unless you have good reason to use it.

delete_option()

Deleting an option is as follows:

 <?php delete_option( 'blogname' ); ?>

This option’s only argument is the name of the option to be deleted. It returns true if the option was deleted, or false if deleting the option failed (or the option did not exist in the first place).

Example: Change the Site Title on April Fool’s

This plugin changes the site title to “WPSnort”—only when it’s April Fool’s (April 1). Here’s the code:

<?php
/*
Plugin Name: WPShout April Fool's Title
*/

function wpshout_april_fools_title() {
	$joke_title = 'WPSnort';
	$site_title = get_option( 'blogname' );

	// Save "normal title" if not currently joke title
	if( $site_title !== $joke_title ) {
		update_option( 'site_normal_title', $site_title );
	}

	// On April 1, set site title to joke title
	$day = date( 'F j' );
	if( $day === 'April 1' ) {	
		update_option( 'blogname', $joke_title );
		return;
	}

	// If normal_title exists and the site title's the joke title, change it back
	$normal_title = get_option( 'site_normal_title' );
	if ( $site_title === $joke_title && $normal_title ) {
		update_option( 'blogname', $normal_title );
	}
}
add_action( 'init', 'wpshout_april_fools_title' );

We chose this an an example of both get_option() and update_option(). The main thing to notice is that we’re registering a new option, 'site_normal_title', which stores the site’s “regular” title so it’s not lost when the April Fool’s title overwrites it. This “regular title” gets saved back to the site’s title anytime it’s not April 1.

By the way, if you wanted to actually implement this functionality, simply filtering the site title on April 1 would be quite a bit more elegant. The complexity of the function above should perhaps be a giveaway: functions that have lots of if-statements and “placeholder” variables can often (although not always) be done a simpler way.

Sidenote: Viewing All Site Options at /wp-admin/options.php

Before we move on, we just want to share a cool trick we picked up a while back. If you want to view all your site’s options—on a single page, with no need to browse your database—simply go to http://yoursite.com/wp-admin/options.php. It’s all there!

That’s the Basics of the Options API

As we hope we’ve made clear, WordPress options are pretty darn simple. And once you understand them, you’ll have a lot of power over the global configuration of your WordPress sites.

Image credit: widenereng


5 Responses

Pingbacks