Читать книгу Professional WordPress Plugin Development - Brad Williams - Страница 80

Retrieving Options

Оглавление

To fetch an option value from the database, use the function get_option().

<?php $pdev_plugin_color = get_option( 'pdev_plugin_color' ); ?>

The first thing to know about get_option() is that if the option does not exist, it will return false. The second thing is that if you store Booleans, you might get integers in return.

The get_option()function accepts the following parameters:

 option: Name of the option to retrieve

 default: Value to return if the option does not exist. The default return value is false.

As an illustration of this behavior, consider the following code block that creates a couple of new options with various variable types:

<?php update_option( 'pdev_bool_true', true ); update_option( 'pdev_bool_false', false ); ?>

You can now retrieve these options, along with another one that does not exist, and see what variable types are returned, shown as an inline comment below each get_option() call:

<?php var_dump( get_option( 'nonexistent_option' ) ); // bool(false) var_dump( get_option( 'pdev_bool_true' ) ); // string(1) "1" var_dump( get_option( 'pdev_bool_false' ) ); // bool(false) ?>

To avoid an error when checking option values, you should store true and false as 1 and 0. This means also that you need to strictly compare the return of get_option() with Boolean false to check if the option exists.

<?php //set the option as true update_option( 'pdev_plugin_enabled', 1 ); if( get_option( 'pdev_plugin_enabled' ) == false ) { // option has not been defined yet // ... echo 'NOT DEFINED YET'; } else { // option exists // ... echo 'OPTION EXISTS!'; } ?>

You can also specify what value you want to be returned if the option is not found in the database, with a second option parameter to get_option(), like in the following example:

<?php $option = get_option( 'pdev_plugin_option', 'Option not found' ); ?>

Professional WordPress Plugin Development

Подняться наверх