0
0
Wordpressframework~5 mins

Options API for site-wide settings in Wordpress

Choose your learning style9 modes available
Introduction

The Options API lets you save and get settings that apply to your whole WordPress site. It helps keep your site settings organized and easy to change.

You want to save a custom setting like a phone number or address for your site.
You need to store a theme or plugin setting that affects the whole site.
You want to let site admins change options from the WordPress dashboard.
You want to keep settings that don't belong to a specific post or user.
You want to retrieve site-wide settings quickly in your theme or plugin code.
Syntax
Wordpress
add_option( string $option_name, mixed $value, string $deprecated = '', string $autoload = 'yes' )

get_option( string $option_name, mixed $default = false )

update_option( string $option_name, mixed $value, string $autoload = null )

delete_option( string $option_name )

add_option saves a new option only if it does not exist yet.

get_option fetches the value of an option, or returns a default if not found.

Examples
Adds a new option named 'site_phone' with the phone number as its value.
Wordpress
add_option('site_phone', '123-456-7890');
Gets the 'site_phone' option value or returns 'No phone set' if it does not exist.
Wordpress
$phone = get_option('site_phone', 'No phone set');
Changes the 'site_phone' option to a new phone number.
Wordpress
update_option('site_phone', '987-654-3210');
Removes the 'site_phone' option from the database.
Wordpress
delete_option('site_phone');
Sample Program

This code shows how to add, get, update, and optionally delete a site-wide setting called 'support_email'. It prints the email before and after updating it.

Wordpress
<?php
// Add a site-wide setting for support email
add_option('support_email', 'help@example.com');

// Get and print the support email
$email = get_option('support_email', 'not set');
echo "Support Email: $email\n";

// Update the support email
update_option('support_email', 'support@example.com');

// Get and print the updated email
$email = get_option('support_email');
echo "Updated Support Email: $email\n";

// Delete the option
// delete_option('support_email');
?>
OutputSuccess
Important Notes

Options are stored in the WordPress database and loaded on every page load if autoload is 'yes'.

Use unique option names to avoid conflicts with other plugins or themes.

Deleting an option removes it completely from the database.

Summary

The Options API stores site-wide settings in WordPress.

Use add_option, get_option, update_option, and delete_option to manage these settings.

This helps keep your site settings organized and easy to change.