Skip to content

Options & Defaults

Xe Plugin provides a centralized, type-safe settings management architecture that links default fallback values with database persistence and a tabbed admin UI.


Architecture Overview

  1. Defaults (src/Defaults.php): Defines default values for all plugin options.
  2. PluginOptions (src/PluginOptions.php): Manages the single combined array stored in wp_options under _xe_plugin_options.
  3. OptionsPage (src/Admin/OptionsPage.php): Renders the settings form and manages WordPress Settings API registration.
  4. Views (src/Admin/Views.php): Renders tab navigation and tab content panels.

1. Setting Default Values (Defaults.php)

Add your default settings keys and fallback values in src/Defaults.php:

namespace Xe_Plugin;

final class Defaults {

  public function all(): array {
    return [
      'currency'     => 'USD',
      'sample'       => esc_html__( 'Sample Text', 'xe-plugin' ),
      'items_per_page' => 20,
    ];
  }

  public function get( string $key, $default = null ) {
    $all = $this->all();
    return $all[ $key ] ?? $default;
  }

}

2. Accessing & Updating Options

Getting an Option:

If an option is not yet saved in the database, PluginOptions automatically falls back to the value defined in Defaults.

$currency = _xe_plugin()->options()->get( 'currency' );

Setting an Option:

_xe_plugin()->options()->set( 'currency', 'EUR' );

Getting All Options:

$all = _xe_plugin()->options()->all();

3. Admin Options Page & Tabs

Xe Plugin includes a tabbed admin settings page built on the WordPress Settings API.

Adding a New Tab

In src/Admin/OptionsPage.php, add a new tab to the tabs action hook and register the tab content:

// 1. In OptionsPage::render()
do_action( '_xe_plugin_options_page_tabs', [
  [ esc_html__( 'General Options', 'xe-plugin' ), 'general', $active_tab ],
  [ esc_html__( 'API Settings', 'xe-plugin' ), 'api', $active_tab ], // New tab
] );

// 2. Render tab content
do_action( '_xe_plugin_options_page_tab', 'api', $active_tab, [ $this, 'api_tab' ] );

Rendering Tab Fields:

public function api_tab() {
  ?>
  <tr>
    <th scope="row">
      <label for="api_key"><?php echo esc_html__( 'API Key', 'xe-plugin' ); ?></label>
    </th>
    <td>
      <input type="text" name="_xe_plugin_options[api_key]" id="api_key" value="<?php echo esc_attr( $this->options->get( 'api_key' ) ); ?>" class="regular-text">
    </td>
  </tr>
  <?php
}

Options are saved automatically under the _xe_plugin_options array when the form is submitted.