Your own setting field

An add-on can add its own page to the KimaAI settings, and when none of the fields KimaAI ships fits a setting (a text, a toggle, a list to choose from, a range and the others), draw it with a React component of its own. Three pieces make it: a settings file in PHP that describes the page and names the component, a script that adds the component with the JS filter kimaai.admin.fieldComponents, and the line that loads the script on the settings page. This guide builds a setting “Greeting” with a count of the characters left. Its values are saved with KimaAI’s settings, by the page’s Save button.

Example

(function (wp) {
  var el = wp.element.createElement;

  function GreetingField(props) {
    var value = props.value || '';
    var max = props.maxLength || 80;

    return el(
      'div',
      null,
      el('input', {
        id: props.controlId,
        type: 'text',
        className: 'regular-text',
        value: value,
        maxLength: max,
        'aria-describedby': props.descriptionId,
        onChange: function (event) {
          props.onChange(event.target.value);
        },
      }),
      el('p', null, max - value.length + ' characters left')
    );
  }

  // A setting row: KimaAI draws the label and description, the component the control.
  GreetingField.settingRow = 'input';

  wp.hooks.addFilter('kimaai.admin.fieldComponents', 'my-addon/greeting-field', function (components) {
    return Object.assign({}, components, {MyAddonGreetingField: GreetingField});
  });
})(window.wp);

This is the add-on’s settings/greeting-field.js. It adds the component under the key MyAddonGreetingField, which the settings file below names. It is plain JavaScript that runs without a build step: wp.element is WordPress’s React, the one KimaAI’s settings use, and wp.hooks the hooks KimaAI’s settings apply. With a build through @wordpress/scripts, import addFilter from @wordpress/hooks and createElement from @wordpress/element instead; the build turns them into the same wp.hooks and wp.element.

The component is defined once, outside the filter’s callback. The settings apply the filter each time they draw fields; a new function on every call would be a new component to React, which draws the field anew and loses the focus while someone types.

The settings file

The add-on’s settings/myAddon.php describes a settings group with one page, one section and the field. Its component is the key the script adds; maxLength is a prop of the add-on’s own, which the component reads:

<?php
return [
  'schema' => [
    'type' => 'object',
    'title' => __('My add-on', 'my-addon'),
    'properties' => [
      'general' => [
        'type' => 'object',
        'title' => __('My add-on', 'my-addon'),
        'link' => 'my-addon',
        'pageTitle' => __('My add-on', 'my-addon'),
        'pageDescription' => __('How my add-on greets visitors.', 'my-addon'),
        'sections' => [
          'welcome' => [
            'icon' => 'MessageSquareText',
            'title' => __('Welcome', 'my-addon'),
          ],
        ],
        'properties' => [
          'greeting' => [
            'section' => 'welcome',
            'type' => 'string',
            'default' => '',
            'component' => 'MyAddonGreetingField',
            'props' => [
              'label' => __('Greeting', 'my-addon'),
              'description' => __('The line my add-on shows above its form.', 'my-addon'),
              'maxLength' => 80,
            ],
          ],
        ],
      ],
    ],
  ],
];

The filter kimaai_settings_schema_files adds the file. Add it when your plugin loads, not on init: KimaAI registers its settings on init, and a file added later cannot be saved.

add_filter(
  'kimaai_settings_schema_files',
  function (array $files): array {
    $files[] = __DIR__ . '/settings/myAddon.php';
    return $files;
  }
);

The group’s key is the file’s name, myAddon, so the setting is stored at myAddon.general.greeting in the option kimaai_options. The page shows at the end of the KimaAI menu, under the group’s title, and opens at admin.php?page=kimaai&tab=my-addon. The page of the filter has the rules of the file: its name, secrets, and what happens to the values when the add-on is deactivated.

Loading the script

The script runs on the KimaAI settings page only, whose hook suffix is toplevel_page_kimaai, with wp-element and wp-hooks as its dependencies:

add_action(
  'admin_enqueue_scripts',
  function (string $hook_suffix): void {
    if ($hook_suffix !== 'toplevel_page_kimaai') {
      return;
    }

    wp_enqueue_script('my-addon-greeting-field', plugins_url('settings/greeting-field.js', __FILE__), ['wp-element', 'wp-hooks'], '1.0.0', true);
  }
);

The settings app draws its first page when the document is ready, after the scripts of the page have run, so the filter is in place by then. Do not load the script with async. KimaAI’s admin script also offers window.kimaaiAdmin.registerFieldComponent(key, component), which adds a component and draws the open page again; it is for a script that can only run after the settings are drawn.

What the component gets

On a settings page a field component gets these props, among a few more that KimaAI’s own fields use:

  • value: the stored value, or the field’s default while none is stored.
  • onChange(value): sets a new value. The page counts it as a change, and Save stores it with the other settings of the page. A string is stored through sanitize_text_field(), unless the field names a sanitize_callback in the settings file.
  • The field’s props from the settings file, as they are: label, description and the add-on’s own, maxLength here.
  • id: the field’s key, greeting.
  • basePath: the setting’s path, myAddon.general.greeting, and className, the same path with hyphens.
  • siblingValues: the stored values of the other fields of the page, by key.
  • settings: all of KimaAI’s settings as the page holds them, to read.
  • On a setting row: layout (row), controlId and descriptionId.

A setting row is the layout of KimaAI’s own settings: the label and description at the start of the row, the control at its end. A component opts in with a static settingRow, input or toggle (for a switch), and the field needs a label. KimaAI then draws the label, pointing at controlId, and the description with the id descriptionId; the component gives its control the id controlId and refers to the description with aria-describedby, as the example does. Without settingRow the field takes the full width of its card, and the component draws its own label.

Reading the value

In the add-on’s PHP, from the option:

$options = get_option('kimaai_options', []);
$greeting = $options['myAddon']['general']['greeting'] ?? '';

What are your feelings