Introduction
Settings let you save and use options in WordPress. Reading and writing settings helps your site remember user choices or preferences.
Jump into concepts and practice - no test required
Settings let you save and use options in WordPress. Reading and writing settings helps your site remember user choices or preferences.
<?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.
<?php
// Read site name
$site_name = get_option('blogname');
echo $site_name;
?><?php // Save a custom color setting update_option('myplugin_color', '#ff0000'); ?>
<?php // Add a setting only if it does not exist add_option('myplugin_text', 'Hello world'); ?>
This code saves a greeting message and then reads it back to show on the page.
<?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; ?>
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.
Use get_option to read saved settings.
Use update_option to save or change settings.
Settings help keep user or site preferences persistent.
get_option is the WordPress function designed to retrieve saved settings. The others are not valid WordPress functions.get_option reads the saved option value, it is the correct choice.update_option, which takes two parameters: the option name and the new value.update_option('site_color', 'blue');. update_option('site_color' => 'blue'); uses an incorrect array syntax. get_option('site_color', 'blue'); uses get_option which reads, not writes. set_option('site_color', 'blue'); uses a non-existent function.$color = get_option('site_color', 'red');
echo $color;get_option returns the default value provided as the second argument, here 'red'.update_option('background_color');update_option requires two parameters: the option name and the new value to set.$size = intval($_POST['font_size']);
if ($size > 0) {
update_option('font_size', $size);
} uses intval to convert input to integer and checks if it is positive before saving.update_option, preventing invalid data.