Wp admin form controls

From Lonsdale201/wp-agent-skills · View interactive version

Wp admin form controls is an AI agent skill from the GitHub repository Lonsdale201/wp-agent-skills. Use WordPress admin form-control widgets that ship in core, `wp-color-picker`, `jquery-ui-datepicker`, `jquery-ui-autocomplete`, and `wp-pointer`. Covers correct script/style enqueues, the missing jQuery UI datepicker CSS, `wpColorPicker` change / clear callbacks, datepicker `yy-mm-dd` formatting pl

How to use this skill

Skill file

WordPress Admin Form Controls

Four small widgets that ship with every WP install and that plugin developers reach for daily — but rarely enqueue correctly. This skill is the recipe sheet.

When to use this skill

Trigger when ANY of the following is true:

Color picker — `wp-color-picker`

Script handle wp-color-picker depends on iris (the underlying picker — Automattic's color library, wp-includes/js/iris.min.js, registered at wp-includes/script-loader.php:1502). The stylesheet wp-color-picker is also registered; you must enqueue it as well.

Enqueue

add_action( 'admin_enqueue_scripts', static function ( string $hook_suffix ): void {
    if ( 'settings_page_myplugin' !== $hook_suffix ) {
        return;
    }
    wp_enqueue_script( 'wp-color-picker' );
    wp_enqueue_style( 'wp-color-picker' );

    wp_enqueue_script(
        'myplugin-color-init',
        plugins_url( 'assets/color-init.js', MYPLUGIN_FILE ),
        array( 'wp-color-picker', 'wp-i18n' ),
        MYPLUGIN_VERSION,
        array( 'in_footer' => true )
    );
} );

Markup + init

<input
    type="text"
    name="myplugin_options[brand_color]"
    value="<?php echo esc_attr( $options['brand_color'] ?? '#0073aa' ); ?>"
    class="myplugin-color-field"
    data-default-color="#0073aa"
/>
jQuery( function ( $ ) {
    $( '.myplugin-color-field' ).wpColorPicker( {
        // Optional — picked up automatically from data-default-color if set on the input.
        // defaultColor: '#0073aa',

        change: function ( event, ui ) {
            // Fires on every color tweak while the picker is open.
            // ui.color is an Iris Color object — call .toString() for the hex.
        },
        clear: function () {
            // Fires when the "Clear" button is clicked.
        },
        palettes: true,                              // false to hide the preset palette row
        // palettes: [ '#0073aa', '#23282d', '#fff' ], // OR an array of hex strings
    } );
} );

Sanitizing server-side

'sanitize_callback' => static function ( $value ): string {
    if ( ! is_string( $value ) ) {
        return '';
    }
    return sanitize_hex_color( $value ) ?: '';
},

sanitize_hex_color() returns null on invalid input — coalesce to '' (or your default) to keep update_option() happy.

Date picker — `jquery-ui-datepicker`

The bundled jQuery UI datepicker. The non-obvious bit: **core does NOT enqueue

a default stylesheet for it**. Ship a small plugin-owned stylesheet; avoid

making wp-admin depend on a third-party CDN. For a simple date-only value,

prefer native <input type="date"> and use jQuery UI only when you need a

consistent calendar UI or constraints native controls cannot provide.

Enqueue

add_action( 'admin_enqueue_scripts', static function ( string $hook_suffix ): void {
    if ( 'settings_page_myplugin' !== $hook_suffix ) {
        return;
    }
    wp_enqueue_script( 'jquery-ui-datepicker' );

    // CRITICAL — core ships no datepicker CSS. Ship your own:
    wp_enqueue_style(
        'myplugin-datepicker',
        plugins_url( 'assets/datepicker.css', MYPLUGIN_FILE ),
        array(),
        MYPLUGIN_VERSION
    );

    wp_enqueue_script(
        'myplugin-date-init',
        plugins_url( 'assets/date-init.js', MYPLUGIN_FILE ),
        array( 'jquery-ui-datepicker', 'wp-i18n' ),
        MYPLUGIN_VERSION,
        array( 'in_footer' => true )
    );

    wp_add_inline_script(
        'myplugin-date-init',
        'window.MyPluginDates = ' . wp_json_encode( array(
            'firstDay' => (int) get_option( 'start_of_week', 0 ),
        ) ) . ';',
        'before'
    );
} );

If you don't want to bundle your own CSS, the jQuery UI "smoothness" theme CSS works:

/* assets/datepicker.css — minimum the picker needs to be usable */
.ui-datepicker { background: #fff; border: 1px solid #c3c4c7; padding: 8px; z-index: 9999; }
.ui-datepicker-header { display: flex; justify-content: space-between; padding: 4px 0; }
.ui-datepicker-prev, .ui-datepicker-next { cursor: pointer; }
.ui-datepicker table { border-collapse: collapse; }
.ui-datepicker td a { display: block; padding: 4px 8px; text-align: center; text-decoration: none; }
.ui-datepicker td a.ui-state-active { background: #2271b1; color: #fff; }

Markup + init

<input
    type="text"
    name="myplugin_options[start_date]"
    value="<?php echo esc_attr( $options['start_date'] ?? '' ); ?>"
    class="myplugin-date-field"
    autocomplete="off"
/>
jQuery( function ( $ ) {
    $( '.myplugin-date-field' ).datepicker( {
        dateFormat:      'yy-mm-dd',           // ISO format for storage. NOT PHP's date() format — jQuery UI's.
        firstDay:        MyPluginDates.firstDay,
        changeMonth:     true,
        changeYear:      true,
        yearRange:       '-5:+5',
        showButtonPanel: true,
    } );
} );

autocomplete="off" on the input prevents the browser from popping its own calendar overlay on top of the jQuery UI one.

dateFormat is jQuery UI's own format string (yy-mm-dd = 4-digit year, 2-digit month, 2-digit day) — NOT PHP's date() syntax. Common confusion source.

Sanitizing server-side

'sanitize_callback' => static function ( $value ): string {
    $raw  = trim( (string) $value );
    $date = DateTimeImmutable::createFromFormat( '!Y-m-d', $raw );
    $err  = DateTimeImmutable::getLastErrors();

    if ( ! $date || ( is_array( $err ) && ( $err['warning_count'] || $err['error_count'] ) ) ) {
        return '';
    }

    return $date->format( 'Y-m-d' ) === $raw ? $raw : '';
},

Autocomplete — `jquery-ui-autocomplete`

Handle jquery-ui-autocomplete (depends on jquery-ui-menu and wp-a11y — the a11y dep means screen readers get role announcements for free).

Enqueue

wp_enqueue_script(
    'myplugin-tag-suggest',
    plugins_url( 'assets/tag-suggest.js', MYPLUGIN_FILE ),
    array( 'jquery-ui-autocomplete', 'wp-api-fetch', 'wp-i18n' ),
    MYPLUGIN_VERSION,
    array( 'in_footer' => true )
);

Source shapes

source can be a static array, a synchronous transform, or an async function that calls response( results ) after wp.apiFetch(). It cannot just return a Promise. Items can be strings or objects with at least label and value; add an id and read it in select when you need a hidden ID field. See reference.md for complete examples.

For user / term suggestions, core ships user-suggest (admin pages only) and tags-suggest — those are wrappers around jquery-ui-autocomplete that hit core admin-ajax endpoints. Worth reusing if your "User" autocomplete maps to WP users — see wp-admin/js/user-suggest.js.

Admin onboarding pointer — `wp-pointer`

The blue floating tooltip core uses for "new feature" onboarding (e.g. the first-time pointer that introduced the Customizer). Useful in plugins for: announcing a new admin menu item after a version bump, drawing attention to a moved button, first-time-tour-style hints.

This is not WordPress 7.1's wp_get_tooltip() / wp_get_toggletip() API.

Pointers are dismissible onboarding UI with user-meta persistence; tooltips are

accessible control names or supporting context. Reach for that core API

when the requested UI is a tooltip/toggletip rather than a one-time tour.

Handle wp-pointer is registered at wp-includes/script-loader.php:860 and depends on jquery-ui-core. The matching stylesheet wp-pointer is registered at :1655 and depends on dashicons — enqueue both.

Dismissal persistence pattern

The hard part isn't showing the pointer; it is not showing it again after dismissal. Core stores dismissed pointer slugs in dismissed_wp_pointers user meta. Enqueue wp-pointer + style only when the slug is not already dismissed, then POST { action: 'dismiss-wp-pointer', pointer: slug } in the pointer close callback. See reference.md for the full safe-content example.

Combining multiple controls on one page

The handles compose cleanly — declare them all as deps, init each in DOM-ready. WP loads each only once even if multiple scripts depend on it.

wp_enqueue_script( 'wp-color-picker' );
wp_enqueue_style( 'wp-color-picker' );
wp_enqueue_script( 'jquery-ui-datepicker' );
wp_enqueue_style( 'myplugin-datepicker' );
wp_enqueue_script(
    'myplugin-fields',
    plugins_url( 'assets/fields.js', MYPLUGIN_FILE ),
    array( 'wp-color-picker', 'jquery-ui-datepicker', 'jquery-ui-autocomplete', 'wp-api-fetch', 'wp-i18n' ),
    MYPLUGIN_VERSION,
    array( 'in_footer' => true )
);

Critical rules

Common AI mistakes

See reference.md for before/after snippets: script without stylesheet, unstyled datepicker, PHP date formats in jQuery UI, returning a Promise from autocomplete source, and pointer UI with no dismissal persistence.

Cross-references

What this skill does NOT cover

References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.