How to Use get_option in WordPress: Simple Guide
Use the
get_option function in WordPress to retrieve a saved setting or option from the database by passing its name as a string. It returns the value of the option or false if the option does not exist.Syntax
The get_option function requires the name of the option you want to retrieve as a string. Optionally, you can provide a default value to return if the option is not found.
- $option: The name of the option to get.
- $default (optional): Value to return if the option does not exist.
php
get_option( string $option, mixed $default = false )
Example
This example shows how to get the site URL stored in the WordPress options and display it. It also shows how to provide a default value if the option is missing.
php
<?php // Get the site URL option $site_url = get_option('siteurl'); // Get a custom option with a default fallback $custom_option = get_option('my_custom_option', 'Default Value'); // Display the values echo 'Site URL: ' . $site_url . "<br>"; echo 'Custom Option: ' . $custom_option; ?>
Output
Site URL: https://example.com
Custom Option: Default Value
Common Pitfalls
Common mistakes when using get_option include:
- Using the wrong option name, which returns
falseor unexpected results. - Not providing a default value when the option might not exist, leading to errors or empty output.
- Expecting
get_optionto return complex data without proper serialization (WordPress handles serialization internally, but custom data must be saved correctly).
php
<?php // Wrong way: misspelled option name $value = get_option('wrong_option_name'); // returns false if not found // Right way: provide default to avoid false $value = get_option('wrong_option_name', 'Default fallback'); ?>
Quick Reference
| Parameter | Description |
|---|---|
| $option | The name of the option to retrieve |
| $default | Value returned if option does not exist (default is false) |
| Return Value | The option value or the default if not found |
Key Takeaways
Use get_option('option_name') to get saved settings in WordPress.
Always check if the option exists or provide a default value to avoid errors.
Option names are case-sensitive and must match exactly what was saved.
WordPress handles serialization for complex data stored as options.
Use get_option inside themes or plugins to access configuration values.