You are currently viewing Developing a Simple Admin Settings Page Plugin for WordPress

Developing a Simple Admin Settings Page Plugin for WordPress

Spread the love

Introduction: Empowering Your WordPress Plugins with User Options

Creating a robust WordPress plugin often goes beyond just adding new functionality; it involves giving users control. A custom administration settings page allows your users to configure your plugin’s behavior, ensuring flexibility and usability. This tutorial will guide you, step-by-step, through building a basic WordPress plugin that adds its own settings page to the admin dashboard, complete with options that can be saved to the database.

Step 1: Setting Up Your Plugin File

Start by creating a new folder in your wp-content/plugins/ directory, for example, my-simple-settings-plugin. Inside this folder, create a PHP file (e.g., my-simple-settings-plugin.php). Add the standard WordPress plugin header comments:

<?php
/**
 * Plugin Name: My Simple Settings Plugin
 * Description: A basic plugin to demonstrate creating an admin settings page.
 * Version: 1.0
 * Author: Your Name
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

Step 2: Registering the Admin Menu Page

Next, we need to tell WordPress to add an item to the ‘Settings’ menu in the admin dashboard. We’ll use the admin_menu action hook and the add_options_page() function.

/**
 * Add a new submenu page under the 'Settings' menu.
 */
function myplugin_add_admin_menu() {
    add_options_page(
        'My Simple Settings',
        'Simple Settings',
        'manage_options',
        'my-simple-settings',
        'myplugin_options_page_html'
    );
}
add_action( 'admin_menu', 'myplugin_add_admin_menu' );

Here’s what each argument means for add_options_page():

  • page_title: The text to be displayed in the browser title bar when the page is active.
  • menu_title: The text to be displayed in the admin menu.
  • capability: The user capability required to access this page (manage_options is common for plugin settings).
  • menu_slug: A unique slug for the menu item.
  • callback: The function that renders the content of the settings page.

Step 3: Creating the Settings Page Content (HTML)

Now, let’s define the myplugin_options_page_html function to display the actual form and content for our settings page. This function will use WordPress’s Settings API functions to render the form correctly.

/**
 * Render the settings page HTML.
 */
function myplugin_options_page_html() {
    // Check user capabilities.
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }

    // Show success/error messages (optional).
    if ( isset( $_GET['settings-updated'] ) ) {
        add_settings_error( 'myplugin_messages', 'myplugin_message', 'Settings Saved', 'updated' );
    }
    settings_errors( 'myplugin_messages' );
    ?>
    <div class="wrap">
        <h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
        <form action="options.php" method="post">
            <?php
            // Output security fields for the registered setting 'myplugin_options'.
            settings_fields( 'myplugin_options' );
            // Output setting sections and their fields.
            do_settings_sections( 'my-simple-settings' );
            // Output save button.
            submit_button( 'Save Settings' );
            ?>
        </form>
    </div>
    <?php
}

Key elements here:

  • <form action="options.php" method="post">: All WordPress settings forms submit to options.php.
  • settings_fields( 'myplugin_options' );: This function outputs hidden fields, including nonces, necessary for form submission. ‘myplugin_options’ is our settings group.
  • do_settings_sections( 'my-simple-settings' );: This displays all registered sections and their fields for the specified menu slug.
  • submit_button( 'Save Settings' );: Renders the standard WordPress save button.

Step 4: Registering Settings, Sections, and Fields

Now, we need to register our actual settings. This is done using the admin_init action hook and functions like register_setting(), add_settings_section(), and add_settings_field().

/**
 * Register plugin settings, sections, and fields.
 */
function myplugin_settings_init() {
    // Register a new setting for 'myplugin_options' group.
    register_setting( 'myplugin_options', 'myplugin_setting_field_one' ); // This registers a single option name.
    // Or, if you want to store all plugin options as an array in one database entry:
    // register_setting( 'myplugin_options', 'myplugin_options_group', 'myplugin_options_sanitize' );

    // Add a new section for 'my-simple-settings' page.
    add_settings_section(
        'myplugin_section_developers',
        'Plugin Settings',
        'myplugin_section_developers_callback',
        'my-simple-settings'
    );

    // Add a new field to the 'myplugin_section_developers' section.
    add_settings_field(
        'myplugin_field_one',
        'My Custom Text Field',
        'myplugin_field_one_callback',
        'my-simple-settings',
        'myplugin_section_developers',
        [ 'label_for' => 'myplugin_field_one' ]
    );
}
add_action( 'admin_init', 'myplugin_settings_init' );

Let’s define the callback functions:

/**
 * Developers section callback function.
 * (Optional) Echoes content for the top of the section.
 */
function myplugin_section_developers_callback() {
    echo '<p>Configure your plugin options below.</p>';
}

/**
 * Field one callback function.
 * Renders the input field for 'myplugin_field_one'.
 */
function myplugin_field_one_callback() {
    // Get the value of the setting we've registered with register_setting().
    $option = get_option( 'myplugin_setting_field_one' );
    ?>
    <input
        type="text"
        id="myplugin_field_one"
        name="myplugin_setting_field_one"
        value="<?php echo esc_attr( $option ); ?>"
        class="regular-text"
    >
    <p class="description">Enter some text for your custom setting.</p>
    <?php
}

// (Optional) Sanitize callback if registering an options array.
// function myplugin_options_sanitize( $input ) {
//     $new_input = array();
//     if( isset( $input['some_field'] ) ) {
//         $new_input['some_field'] = sanitize_text_field( $input['some_field'] );
//     }
//     return $new_input;
// }

Explanation of new functions:

  • register_setting( $option_group, $option_name, $args ): This is crucial. It tells WordPress to store the input field’s value (identified by name="$option_name") into the database under the specified $option_name. We’re using myplugin_setting_field_one as our option name, which will be stored as a single entry in the wp_options table. The $option_group (myplugin_options) links it to our form.
  • add_settings_section( $id, $title, $callback, $page ): Defines a logical grouping for related settings fields. $page must match the menu_slug from add_options_page().
  • add_settings_field( $id, $title, $callback, $page, $section, $args ): Defines an individual input field. The $callback function is responsible for rendering the actual HTML for the input.

Step 5: Retrieving and Displaying Saved Options

In the myplugin_field_one_callback(), notice the line $option = get_option( 'myplugin_setting_field_one' );. This retrieves the currently saved value for our setting from the wp_options table. We then use esc_attr( $option ) to safely pre-fill our input field, ensuring a good user experience and preventing XSS vulnerabilities.

Conclusion: Your First Admin Settings Page is Live!

You now have a fully functional, albeit simple, admin settings page for your WordPress plugin! Activate your plugin from the ‘Plugins’ menu, navigate to ‘Settings > Simple Settings’, and you’ll see your custom field. Enter some text, save it, and refresh the page – your text will persist. This foundation can be expanded with more complex fields (checkboxes, select boxes, radio buttons), validation, and comprehensive sanitization for robust, production-ready plugins.

Remember to always prioritize security: validate and sanitize all user input before saving it to the database, and escape all output when displaying it.

Leave a Reply