Dani 1 min read
January 17, 2024 (last revised)

Creating a WordPress Options Page with PHP

Adding a custom options page to your WordPress site enhances flexibility. Follow this guide to create one using PHP, simplifying customization. Let’s dive into the code and explanation!

<?php

// Add Options Page
function custom_options_page() {
    add_menu_page(
        'Custom Options',
        'Custom Options',
        'manage_options',
        'custom-options',
        'custom_options_page_callback'
    );
}
add_action('admin_menu', 'custom_options_page');

// Options Page Callback
function custom_options_page_callback() {
    ?>
    <div class="wrap">
        <h1>Custom Options Page</h1>
        <form method="post" action="options.php">
            <?php settings_fields('custom_options_group'); ?>
            <?php do_settings_sections('custom-options'); ?>
            <?php submit_button(); ?>
        </form>
    </div>
    <?php
}

// Register Settings and Fields
function custom_options_settings() {
    register_setting('custom_options_group', 'custom_option_name');
    add_settings_section(
        'custom_options_section',
        'Custom Settings',
        'custom_options_section_callback',
        'custom-options'
    );
    add_settings_field(
        'custom_option_name',
        'Custom Option',
        'custom_option_callback',
        'custom-options',
        'custom_options_section'
    );
}
add_action('admin_init', 'custom_options_settings');

// Section and Field Callbacks
function custom_options_section_callback() {
    echo 'Customize your options below:';
}

function custom_option_callback() {
    $option_value = get_option('custom_option_name');
    echo "<input type='text' name='custom_option_name' value='$option_value' />";
}

Place the provided PHP code in your WordPress theme’s functions.php file, typically located in your active theme folder.

Explanation:

  1. Add WordPress Options Page:
    • add_menu_page function adds a custom options page to the admin menu.
  2. Options Page Callback:
    • custom_options_page_callback function displays the content of the custom options page.
  3. Register Settings and Fields:
    • register_setting registers the option in the database.
    • add_settings_section and add_settings_field define the sections and fields on the options page.
  4. Section and Field Callbacks:
    • custom_options_section_callback and custom_option_callback provide content for the sections and fields.

Custom Options Page

By following this example, you can easily create a customizable feature in WordPress using PHP. This provides a foundation for expanding functionality and tailoring your WordPress site to your specific needs. For a deeper dive into customizing your WordPress site, check out our guide on Creating a WordPress Options Page with PHP. Happy coding!

Admin Menu PHP Wordpress