...

/

Creating Custom Setting Page with Submenu

Creating Custom Setting Page with Submenu

Learn to add a settings page with a submenu.

Before we move to submenus, we will add some additional features to the plugin.

Prevent direct access of plugin file

It’s important to prevent the direct access of the plugin file, which could lead to unexpected behavior or execution of the file if accessed directly from the plugin folder. To avoid this, we can add a safeguard in the form of the following line of code that prevents the execution of the file when the URL of the PHP file is viewed in the browser.

<?php
if( !defined('ABSPATH') )
exit; //exit if directly accessed
Prevent direct access of plugin file

ABSPATH is a WordPress constant that defines the absolute path to the WordPress installation directory. By checking if it is defined, the code ensures that it is executed only in the context of a WordPress installation, and not outside of it. This security measure prevents the code from being executed if it is accessed directly from the file system, rather than being called through the WordPress core.

Adding a top level admin dashboard menu

The pmp_menu callback function that we hooked on to the adin_menu hook created a link in the "Settings" option of the admin sidebar that takes us to the plugin’s setting page. We used the add_options_page function which is reproduced below:

<?php
//callback to create settings page/link in admin menu
function pmp_menu(){
add_options_page('Post Metrics Settings', 'Post Metrics', 'manage_options',
'post-metrics-settings-page', array($this, 'render_settings_page'));
}
Adding a top level admin dashboard menu

An explanation of the arguments can be found in the Using WordPress API Settings lesson.

If instead of adding the plugin settings inside the "Settings" menu of the admin dashboard, we want to create a separate menu icon for the plugin, we need to use ...