0
0
Wordpressframework~5 mins

Reading and writing settings in Wordpress

Choose your learning style9 modes available
Introduction

Settings let you save and use options in WordPress. Reading and writing settings helps your site remember user choices or preferences.

You want to save a site title or description set by the admin.
You need to store user preferences like color scheme or layout.
You want to keep track of plugin options that users can change.
You want to read saved settings to show different content.
You want to update settings when a form is submitted.
Syntax
Wordpress
<?php
// To read a setting
$value = get_option('option_name');

// To write or update a setting
update_option('option_name', 'new_value');

// To add a new setting if it does not exist
add_option('option_name', 'default_value');

// To delete a setting
delete_option('option_name');
?>

get_option reads the saved value or returns false if not found.

update_option adds or updates the value automatically.

Examples
This reads the WordPress site title and prints it.
Wordpress
<?php
// Read site name
$site_name = get_option('blogname');
echo $site_name;
?>
This saves a red color value for a plugin setting.
Wordpress
<?php
// Save a custom color setting
update_option('myplugin_color', '#ff0000');
?>
This adds a new setting with default text if it is not already saved.
Wordpress
<?php
// Add a setting only if it does not exist
add_option('myplugin_text', 'Hello world');
?>
Sample Program

This code saves a greeting message and then reads it back to show on the page.

Wordpress
<?php
// Save a greeting message
update_option('greeting_message', 'Welcome to my site!');

// Read and display the greeting
$message = get_option('greeting_message');
echo $message;
?>
OutputSuccess
Important Notes

Settings are stored in the WordPress database and persist between page loads.

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

Always sanitize and validate data before saving settings for security.

Summary

Use get_option to read saved settings.

Use update_option to save or change settings.

Settings help keep user or site preferences persistent.