A Clean Way to Display get_option in WordPress

Getting values from database using WordPress Hook function might be troublesome. You have to create a fallback statement in case unexpected values or output occurs. When you read its official get_option documentation you might come up for the solution of putting a default value when the option key has no corresponding value e.g. get_option('your-field-key', 'your-field-value'). Misconceptions on doing that is that, when option key exist and has no value, it actually returns nothing.

So the safer way to solve get_option() output, let’s create a function sanitizing the get_option results.

 * Get Options Fixes
 * @param $db_field string
 * @param $default string
function cool_option($db_field, $default){
  $get_option = get_option($db_field);
  // if it is empty string, 0, or null, just return the default value.
    $get_option = $default;
  return $get_option;

Then when you echo that value, you can just call a one line of code

echo cool_option('your_wp_field_key', 'your default value');

I hope you could learn from this piece of code, just comment below for more clarification, enjoy coding!

A Clean Way to Display get_option in WordPress1.67/5 (33.33%) 12 votes

Elvin is one of the contributors of InnoveDesigns.com. He has been creating Wordpress Plugins, Magento Extensions, & Mobile Applications. If you find this article useful, please Follow him on .

Published under Wordpress