...

/

Using WordPress Settings API: Part II

Using WordPress Settings API: Part II

Learn to build a form that shows the settings for our plugin.

The settings page for the Post Metrics plugin shows one option to set the display location. The default value is Beginning of post but even after changing it to End of post when we refresh the page, it shows the default value.

Fetch the setting from database

To make the HTML select element show the actual setting, we will edit the display_location_html function. This function is responsible for showing the select element with options for display location. We will use PHP to output the selected attribute from the database For every <option>, we will check if the selected value from database matches that attribute’s value field.

selected is a WordPress function which compares two arguments and marks the option selected if they are equal. This function takes two arguments.

  1. The first argument is the value from the database. The get_option function loads the value of the setting from the database.

  2. The second argument is the value attribute, which is 0 for the first option tag and 1 for the second tag.

<?php
class PostMetricsPlugin {
//function to render the Display Location setting
function display_location_html() { ?>
<select name= "pmp_location">
<option value="0" <?php selected(get_option('pmp_location'), '0') ?>>Beginning of post</option>
<option value="1"<?php selected(get_option('pmp_location'), '1') ?>>End of post</option>
</select>
<?php
}
}
Fetch the setting from database

The get_option() function in WordPress is designed to have minimal impact on performance because it retrieves values from the database in a single trip. When WordPress loads options from the wp_options table, it loads all of them at once by default. The autoload column in this table is set to yes for our setting, as well as for all other options in the table. As a result, WordPress fetches all of these settings in one go, rather than making multiple trips to the database.

If we save and refresh the plugin settings page, we can see that the selected option for the display location is shown.

Checkboxes for read time, word count and paragraph count

Now we will add more settings to our plugin. These pertain to what the user wants to display in terms of post metrics. The user can choose from read time, word count, and paragraph count.

Recall from the previous lesson, the three steps for adding a setting:

  1. Define the section on the page where the setting will go. ...