Using WordPress Settings API: Part I
Learn to create a form with sections and fields and let WordPress loop through them to display the settings page for the plugin.
Plugin settings page
In this lesson, we will create a settings page for the plugin. For example, maybe a user would only want to display the read time of a post. Or maybe some users want to show the word and paragraph count of the post along with the read time. This is where the plugin setting screen comes into play. We will let the user choose the following:
Select the position of the metrics at the start or end of the post.
Checkboxes to display the read time, word count, and paragraph count.
Enter the words per minute to calculate the read time.
We will create a settings page for the plugin and add a link in the admin sidebar that leads to our plugin settings page.
To add a settings page we will add an action to the admin_menu
hook. At this hook, we will call a function. Instead of coming up with a unique function name, we will use an alternate approach.
PHP classes
Coming up with unique function names is a tiring process. It also makes the names very long. By using classes we can get rid of the unique name restriction as the functions are scoped inside the class and will not clash with other functions across the WordPress platform.
We only need to ensure that the class name is unique. Let’s call our class PostMetricsPlugin
. Open the post-metrics-plugin.php
file created in the last lesson. Delete the add_metrics_to_post
method and in its place, define the PostMetricsPlugin
class below the comment section as follows:
Get hands-on with 1200+ tech skills courses.