What is the use of get_option method

I am a new learner of WordPress plugin. recently I came across a method get_option(). When I pass the page parameter of add_settings_field() function then it outputs all the input fields (checkboxes) of that page as true if checkbox is checked and false if checkbox is unchecked.

I didn’t understand how does the function know that whether a checkbox is checked or not. May be I’m not able to focus the part of code where this is being decided.

I will be grateful if anyone explains to me the use of the function and how it works?

1 Answer
1

Well, as you can see in the contributed example to the WordPress Reference, it is not that add_settings_field magically knows about a setting being true or false, and it is not limited to checkboxes (boolean flags):

Instead, the function signature states clearly that the $callback parameter it is required. And the introduction says:

The $callback argument should be the name of a function that echoes out the html input tags for this setting field. Use get_option() to retrieve existing values to show.

Maybe it should say that get_option it’s the recommended (as it is the easier) way to show stored setting in the database, but you decide how do you use it in your callback function, and how that control renders the option.

In this example provided, yes, it is a checkbox that is checked (or not), depending on the value stored:

function callback_input_myid() {
    echo "<input type="checkbox" id='mynewcheckboxID' value="1""
    if ( get_option('mynewcheckboxID') == '1' ) {
        echo ' checked';
    }
    echo '/>';
}

But as I’ve said before, it is not limited to boolean settings and checkboxes therefore. You could store a text, a color and your function render a ColorPicker, to store a date therefore render a DatePicker, even store a file in base64, however I’m not sure that should be advisable, just saying what is rendered and what option is retrieved it is entirely your responsibility.

Put it simple, get_option is just a convenient and pluggable way to do a SELECT FROM options table.

Leave a Comment