How to store my custom values?

When you dive into the so called Settings API (something so poor even the core doesn’t use it), you will probably get the advice to store all your data in one single option, not in many. And it sounds just logical: Less options are faster than more options, right?

It depends.

MySQL doesn’t know anything about arrays, so we have to convert this data type into something MySQL understands: a string. WordPress will use the function serialize() for that. An array like …

$array = array (
	'first_name' => 'Thomas',
	'last_name'  => 'Scholz'
);

… will be stored as:

a:2:{s:10:"first_name";s:6:"Thomas";s:9:"last_name";s:6:"Scholz";}

And when you fetch that value from the database, with get_option() for example, WordPress will inspect and unserialize it if needed with maybe_unserialize().

Yes, the plain MySQL query will be faster. But is it worth it?

The next option is a custom table. This requires more efforts, and you have to write large parts of your user interface for yourself. On the other hand, you can fetch just the values you actually need, the table can use fine-tuned indexes, and you can change its structure easier. Stephen Harris has written a good tutorial about custom tables.

So when to use what?

There is no golden rule that fits all use cases.

When you start writing a plugin, it isn’t always clear which way is the best. Store your plugin’s version number as an option, so you know when you have to convert existing data in an installation routine after an update when you change your mind.

And no matter what you do: always clean up on uninstallation; delete anything the user will not need anymore. Make it an habit to write that part before you finish the code to store the data.

Author:

Web developer since 1998, moderator on WordPress Stack Exchange, author, manic reader.

Code is my drug.

Find Thomas Scholz on toscho.de⁠, ⁠, ⁠, ⁠, ⁠, ⁠, and .

1 Comment

  1. webaware29.07.2013 01:40

    +1 to all above.

    Perhaps also worth mentioning is that options your plugin / theme / whatever will use on practically every page / post can be autoloaded, but use-specific options should not be autoloaded; often, plugins put chunks of HTML or templates into options, and these should not be autoloaded because they serve only to chew up memory on pages / posts where they are unused.

    Reply

Leave a Reply

Your email address will not be published.