When working with a WordPress site to build or customize your theme, you may need to get different custom options that you store in the database. In order to do that, you need to use the get_option function. Let’s take a look at how this function works below.
The get_option Function Definition And Arguments
<?php
function get_option(string $option, mixed $default = false)
As you can see, the function takes 2 arguments:
- $option – the name of the option that you want to retrieve
- $default – optional value that will be returned if the option doesn’t exist
How To Use The get_option Function
Let’s say we want to retrieve the name of the site and display it:
<?php
// Displays the name of the site
echo get_option('blogname');
The blogname is a default option that is always available in WordPress.
Now, let’s say we have a list of random quotes and we want to display one of them. Here is how we may be able to do that:
<?php
// Get a list of quotes. Return an empty array if option doesn't exist.
$quotes = get_option('random_quotes', []);
if (empty($quotes)) {
echo 'No quotes';
return;
}
// Get a random key
$randKey = array_rand($quotes);
// Echo option
echo $quotes[$randKey];
Functions Similar To get_option Function
- get_site_option(string $option, mixed $default = false, bool $deprecated = true) – retrieves an option value for the current network based on name of option.
- add_option(string $option, mixed $value = ”, string $deprecated = ”, string|bool $autoload = ‘yes’) – adds a new WordPress option to the database.
- update_option(string $option, mixed $value, string|bool $autoload = null) – updates the value of an option that was already added.
Wrapping Up
As you can see, the get_option function can be handy in some situations especially when you’re building a custom theme or plugin.