How to read and update options with get_option and update_option in WordPress

Contents

Overview

This article explains in detail how to read and write WordPress options using the core functions get_option and update_option. It covers function signatures, parameters, return values, behavior with autoload, serialization, multisite differences, caching, hooks triggered by option changes, recommended best practices (security and performance), and many practical, copy-paste examples.

What are WordPress options?

Options are small pieces of persistent configuration stored in the database (the wp_options table for single-site installations). Plugins and themes commonly use options to store settings. Options are usually simple scalars but can also be arrays or objects — WordPress will serialize/unserialize automatically.

Function reference summary

Function Purpose
get_option Read an option from the database/option cache returns stored value or default if not present.
update_option Create or update an option returns success state clears caches and fires hooks.

get_option — details

Signature get_option( string option, mixed default = false )
Parameters
  • option (string) — option name (case-sensitive). Use a unique prefix (plugin/theme slug) to avoid collisions.
  • default (mixed) — value returned if option does not exist. If omitted, get_option returns false when the option does not exist.
Return Stored value (any type), or default if not present. If the stored option value is an array/object it will be unserialized and returned as that type.
Notes
  • Autoloaded options are loaded into memory on each page load. Non-autoloaded options are fetched from the DB when requested.
  • get_option uses WP object cache repeated calls are fast.

update_option — details

Signature update_option( string option, mixed value )
Parameters
  • option (string) — option name.
  • value (mixed) — the value to store. Arrays/objects are serialized automatically.
Return
  • true — option was added or updated (value changed or added).
  • false — value did not change or update failed.
Notes
  • If the option does not exist, update_option will call add_option internally. That call defaults the options autoload to yes. If you need autoload=no for large values, call add_option explicitly with autoload no before update_option.
  • update_option clears relevant caches and triggers update hooks so other parts of code can react to the change.

Autoload and performance considerations

Each option in the wp_options table has an autoload column (yes or no). All options with autoload=yes are loaded into memory on every page load using wp_load_alloptions(). Because of that:

  • Do not set large arrays or heavy blobs as autoload=yes. They will increase page-load memory usage.
  • When creating options for large or rarely accessed data, use add_option(…, value, no) so autoload is disabled.
  • If you call update_option and the option did not previously exist, it will be created as autoload=yes. To avoid that, create it first with add_option(name, value, , no) and then update it.

Serialization and data types

WordPress handles serialization automatically. You can store arrays or objects directly with update_option and get them back unchanged with get_option. Internally the value is serialized (via maybe_serialize) and saved into the DB get_option will unserialize it before returning.

Sanitization, escaping and security

Always sanitize data before saving options (server-side) and escape output when rendering in HTML. For example:

  • Use sanitize_text_field(), intval(), floatval(), wp_kses_post(), or custom sanitizers depending on expected content.
  • For complex settings pages use register_setting() and callbacks to sanitise.
  • Escape when outputting: esc_html(), esc_attr(), wp_kses(), etc.

Hooks related to options

When options are added, updated, or deleted WordPress fires actions and filters. Useful hooks:

  • add_option / added_option — fired when a new option is added.
  • update_option and the dynamic update_option_{option} — fired when an option is updated (you can hook to a specific option by name).
  • deleted_option / delete_option — when an option is removed.

Example of hooking to a single option update (dynamic hook). The callback receives the old and new values:


Multisite considerations

  • On a multisite network, regular blog options live in each sites wp_{blog_id}_options table. Use get_option/update_option for site-specific options within the current blog context.
  • For network-wide options stored in the sitemeta table, use get_site_option and update_site_option.
  • If you need to read or write an option for a different blog use switch_to_blog( blog_id ) and restore_current_blog().

Common pitfalls and how to avoid them

  • Accidentally autoloading large options: If you need large or seldom-used data, store it with add_option(…, no) or use a custom table or the transient API.
  • Assuming get_option always returns false: get_option can return any type. If the saved value is boolean false or empty string, it might be indistinguishable from not found unless you use a non-false default parameter.
  • Options collision: Always prefix option names with a plugin or theme slug, e.g. myplugin_setting_enable_feature.
  • Race conditions: When multiple processes update the same option concurrently, you may want to implement locks or use update_site_option if relevant in multisite context.

When to use options vs transients vs custom tables

  • Options: small configuration or settings data that must persist long-term.
  • Transients: temporary cached data with expiration (use set_transient/get_transient). They can use object cache backends and are better for expensive-to-generate values.
  • Custom tables: large, complex relational data sets or very large payloads that would bloat the options table or autoload memory.

Practical examples

1) Simple read with default fallback


2) Save a simple string option


3) Save and read an array (no manual serialization needed)

 true,
    per_page => 20,
    labels => array( one => One, two => Two ),
)

// Save
update_option( myplugin_settings, settings )

// Read back
loaded = get_option( myplugin_settings, array() )
if ( is_array( loaded ) ) {
    // Use loaded[per_page], etc.
}
?>

4) Avoid creating an autoloaded option by using add_option first


5) Using update_option on plugin activation to set defaults

 true,
        api_key => ,
    )
    // Only add defaults if option is missing.
    if ( false === get_option( myplugin_settings ) ) {
        add_option( myplugin_settings, defaults )
    }
}
register_activation_hook( __FILE__, myplugin_activate )
?>

6) Reacting to a specific option change


7) Multisite: using network options


Debugging and inspecting options

To inspect raw options you can query the database directly (use wpdb), but prefer WP functions while developing. Example to view option value in debug log:


Best practices checklist

  1. Prefix option names to avoid collisions: e.g. myplugin_setting_name.
  2. Sanitize before saving and escape before outputting.
  3. Dont autoload large data create such options with add_option(…, no).
  4. Use transients for caching expensive queries or external data with an expiration.
  5. Use get_site_option/update_site_option for multisite network-wide settings.
  6. Use hooks (dynamic update_option_{option}) to react to important changes.
  7. For very large data or relational structures, consider a custom table instead of bloating wp_options.

Useful links

Summary

get_option and update_option are the primary way to read and write WordPress options. They handle serialization automatically, use the object cache for performance, and fire hooks to let other code react to changes. Be mindful of autoload behavior, sanitize inputs, escape outputs, and choose the appropriate storage mechanism (option, transient, or custom table) depending on size and usage patterns.



Acepto donaciones de BAT's mediante el navegador Brave 🙂



Leave a Reply

Your email address will not be published. Required fields are marked *