get_theme_mod come with a handy second parameter to define a default value if the option/theme mod is not available. However, sometimes the return value of these function is still empty despite having a default value set. We look into it how that’s possible.
Especially when I began developing for WordPress I struggled more than once with these default values and asked myself why the return value can be empty. When looking into the documentation of
get_theme_mod, it will not be clear at all. The second parameter
$default has the following documentation there:
Theme modification default value.get_theme_mod() | Function | WordPress Developer Resources
Looking into the documentation of the similar second parameter
get_option, things become more clear:
Default value to return if the option does not exist.get_option() | Function | WordPress Developer Resources
The default value is only used if the option doesn’t exist at all. So even if the option exists in the database with an empty value, an empty value is returned, not the default value set.
To overcome this, you can use the short-ternary operator to get the default value if the value of the option/theme mod is empty:
$option_value = get_option( 'my_option', 'default value' ) ?: 'default value';Code language: PHP (php)
If the option doesn’t exist,
get_options returns the default value set as second parameter. If it exists but is translated to be empty, the alternative default value of the short-ternary operator is used as value. This way you can be sure that the value stored in
$option_value is never empty.
The default parameter in
get_theme_mod works identical at first sight but is also processed by a
sprintf function to make use of the template directory URI and the stylesheet directory URI. So if you need that in your default value and use the short-ternary from above, make sure to apply the same
sprintf function for the additional default value as well.