arraypress / wp-field-kit
One field engine — type registry, accessible renderers, sanitizers, conditional logic and REST search — shared by the wp-register-*-fields libraries.
Requires
- php: >=8.3
Requires (Dev)
- phpcompatibility/phpcompatibility-wp: ^2.1
- phpunit/phpunit: ^12.0
- squizlabs/php_codesniffer: ^3.13.5
- wp-coding-standards/wpcs: ^3.4
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
This library has moved. It is now part of
sugarcommerce/fields(namespaceSugarCommerce\Fields, PHP 8.3+). That package's README has a "Moving from arraypress/wp-*" table. This repository is archived and read-only.
Field Kit
Render, sanitise and store an admin form field — once, so nothing has to render one again.
What it does
Every library that puts a field on a screen ends up writing the same three
things: the markup, the sanitising, and the reading and writing of wherever
the value lives. Do it five times and you have five subtly different text
inputs, four of which forget esc_attr somewhere.
This is the one implementation. A field describes itself; the kit renders it, coerces what comes back by type, and reads and writes it through a context — post meta, term meta, an option, an array — so the same declaration works wherever the screen happens to be.
Features
- Render any of the field types below, escaped, with a label and description
- Sanitise on save by type, rather than a callback per field
- Store to post meta, term meta, user meta, an option or a plain array
- Show a field only when another has a given value
- Search posts, users or terms from one endpoint, whatever the field type
- Group fields into tabs or collapsible sections
- Sit two short fields on one line with
'width' => 'half' - Take an amount with its currency symbol inside the control
- Fill a select from a named preset — roles, timezones, countries — with one string
- Put a unit inside any input — a
$before a price,daysafter a number - Reveal a password as it is typed, and count characters against a limit
- Fold a repeater's rows away, each titled by one of its own fields
- Reorder a repeater by dragging its handle, or from the keyboard
- Refuse a value that fails a rule — required, email, url, your own callable — and say why
- Encrypt a value at rest, for an API key
- Keep a stored secret when its box is saved empty, since a password is never shown back
- Remove a stored secret with the button beside its box, which rides the form's own save
- Get told, under
WP_DEBUG, when a config key does nothing - Pick a colour with the browser's own picker, paste a hex beside it, or choose a preset
- Pick an icon from every registered set -- Heroicons, WordPress's own, Dashicons, a theme's -- in a searchable dialog
- Register an icon set from a folder of SVGs or a callback, and draw any stored icon as clean inline SVG
Installation
composer require arraypress/wp-field-kit
Quick start
use ArrayPress\FieldKit\FieldSet; use ArrayPress\FieldKit\Context\OptionContext; $set = new FieldSet( [ 'site_name' => [ 'type' => 'text', 'label' => __( 'Site name', 'my-plugin' ) ], 'per_page' => [ 'type' => 'number', 'label' => __( 'Per page', 'my-plugin' ), 'min' => 1 ], ], new OptionContext( 'my_plugin' ), 'my_plugin' ); echo $set->render(); // Each value is coerced by its own type; a key you did not declare is dropped. $set->save( $_POST['my_plugin'] ?? [] );
Field types
Text and numeric
: text email url tel password hidden number percentage range textarea code wysiwyg code_generator
Date, time and colour
: date time datetime color gradient date_range time_range
Choice
: select enhanced_select select_multiple checkbox toggle radio checkbox_group button_group card_choice country region currency
Relational — one search endpoint behind all of them
: post page user taxonomy ajax tags
Media
: image file file_url gallery files
Compound
: group repeater list key_value sortable providers dimensions amount_type money flexible
Layout and display
: heading separator message html link clipboard oembed custom tab accordion icon nav_menu
Purpose-built
: license email_editor action_button
Beyond the quick start
Sanitising coerces; it does not refuse. required and validate do the
refusing on the server: a value that fails is left where it was, every other
field is saved, and the message is kept for the next render. Options can name
a preset instead of listing choices. Any single-line input takes a prefix
or a suffix, a password can offer a reveal, and a maxlength shows a count. A
region follows the country beside it, starts again when the country changes,
and with 'searchable' => true has a search box over its list.
A password is never shown back, so its box saved empty keeps what is stored.
Beside a box with something stored there is a Remove button: it marks the
field, the mark is submitted with the form as {prefix}[__clear][{key}]
(FieldSet::CLEAR_KEY), and save() deletes the value. A typed value wins
over the mark, a required secret has no button, and 'removable' => false
leaves it off -- which is right for a surface that sanitises a submission
into an empty store and saves it itself, where the mark has nothing to act on.
$set = new FieldSet( [ 'contact' => [ 'type' => 'email', 'label' => __( 'Contact', 'my-plugin' ), 'required' => true ], 'notify' => [ 'type' => 'tags', 'label' => __( 'Notify', 'my-plugin' ), 'validate' => 'email' ], 'api_key' => [ 'type' => 'password', 'label' => __( 'API key', 'my-plugin' ), 'reveal' => true, 'validate' => static fn( $value ) => str_starts_with( $value, 'sk_' ) ? true : __( 'An API key starts with sk_.', 'my-plugin' ), ], 'role' => [ 'type' => 'select', 'label' => __( 'Notify role', 'my-plugin' ), 'options' => 'roles' ], 'price' => [ 'type' => 'number', 'label' => __( 'Price', 'my-plugin' ), 'prefix' => '$', 'step' => 0.01 ], 'discount' => [ 'type' => 'percentage', 'label' => __( 'Discount', 'my-plugin' ) ], 'tagline' => [ 'type' => 'text', 'label' => __( 'Tagline', 'my-plugin' ), 'maxlength' => 80 ], 'country' => [ 'type' => 'country', 'label' => __( 'Country', 'my-plugin' ), 'continents' => true ], 'region' => [ 'type' => 'region', 'label' => __( 'State or province', 'my-plugin' ), 'country_key' => 'country' ], 'currency' => [ 'type' => 'currency', 'label' => __( 'Currency', 'my-plugin' ) ], ], new OptionContext( 'my_plugin' ), 'my_plugin' ); $set->save( $_POST['my_plugin'] ?? [] ); // Rendered after a save in the same request, each failing field is marked // and shows its message; errors() has them for a notice of your own. echo $set->render();
Rules are email, url, numeric, integer, slug and alphanumeric; a
callable returns true, a message or a WP_Error; on tags and list the
rule applies to each item; validate() checks without storing. Presets are
roles, post_types, taxonomies, pages, timezones, image_sizes,
page_templates, cron_schedules, countries and currencies, resolved on
render and filterable, with Presets::register() for your own. Countries and
regions come from arraypress/wp-countries, currencies from
arraypress/wp-money; a region is a select where the country has
subdivisions on file and a text input where it does not.
Colour
The color field is the browser's own colour input -- the operating
system's picker, eyedropper and all -- drawn as a chip inside a box holding
the hex. Either moves the other: pick a colour and the hex follows, paste
#E8A5C4 or e8a5c4 and the chip follows. Clear empties both. presets
adds a row of swatches, as a list or with names:
'tint' => [ 'type' => 'color', 'label' => __( 'Colour', 'my-plugin' ), 'presets' => [ '#e8a5c4' => __( 'Rose', 'my-plugin' ), '#3858e9' => __( 'Blue', 'my-plugin' ), '#1e1e1e' ], ],
The hex box is the field: it has the name and the label, so the form works
with the script off. What is stored is #rrggbb, lowercase, or empty --
Color::hex() is the rule, and any form of a hex is read. 'picker' => 'wordpress' gives core's Iris picker instead, for its look or its alpha
channel; alpha alone implies it, and only then is an rgba() kept. Only a
field that asks for Iris loads it.
Icons
The icon field is a button showing the chosen icon and its name. It opens
a dialog -- search box, a tab per set, a grid of icons -- that asks the
kit's /icons endpoint for a page at a time, so a set of thousands costs
nothing until somebody opens it. Arrow keys move through the grid, Enter
chooses, Escape closes (and only the dialog, inside a flyout panel), and
focus goes back to the button. sets limits the field to some of them:
'badge' => [ 'type' => 'icon', 'label' => __( 'Badge', 'my-plugin' ), 'sets' => [ 'heroicons-outline', 'heroicons-solid' ], 'placeholder' => __( 'No badge', 'my-plugin' ), ],
An icon is stored as set:name -- heroicons-outline:shopping-cart,
dashicons:cart -- at most 48 characters for any built-in, and is held to
the registry when saved: an unknown set or name, or a set the field does not
offer, is stored as empty. The old form, a whole Dashicons class
(dashicons-cart), is read as dashicons:cart.
Drawing one, anywhere -- a template, an email, a REST response:
use ArrayPress\FieldKit\Icons\Icons; echo Icons::svg( $value, [ 'size' => 24, 'class' => 'shop-icon' ] ); // aria-hidden, currentColor echo Icons::svg( $value, [ 'label' => __( 'Basket', 'my-plugin' ) ] ); // role="img" with a name Icons::exists( $value ); // a real icon? Icons::label( $value ); // "Shopping cart" Icons::sanitize( $value ); // `set:name`, or ''
Taking an icon in a library
A library whose arguments take an icon -- a report tile, a table's empty
state, a flyout's menu item -- draws it with Icons::render(), which reads
both forms a caller may pass:
echo Icons::render( 'heroicons-outline:chart-bar', [ 'class' => 'my-tile__icon' ] ); // <svg width="20" height="20" class="arraypress-icon my-tile__icon" aria-hidden="true" …> echo Icons::render( 'chart-bar', [ 'class' => 'my-tile__icon' ] ); // or 'dashicons-chart-bar' // <span class="dashicons dashicons-chart-bar arraypress-icon my-tile__icon" aria-hidden="true"></span>
A set:name value is inline SVG in currentColor; a bare Dashicons name, the
form libraries took before there were sets, is the font's span exactly as it
was (with the dashicons style enqueued), so existing callers see no change.
Either way the element has the arraypress-icon class (Icons::ICON_CLASS,
the same in every prefixed copy), so one rule sizes both:
.my-tile__icon.arraypress-icon { width: 24px; height: 24px; font-size: 24px; }
An SVG with no size is 20 by 20 -- a Dashicon's box -- set as attributes, so
the stylesheet still wins. label makes it role="img" with that name;
otherwise it is aria-hidden. A value that is neither form, or names an icon
no set has, draws nothing. Icons::is_set_value() tells the two forms apart,
for a library that also accepts a URL or an emoji. The kit's own icon
arguments -- a button's, a badge's, a card choice's -- take either form.
The kit's own icons
The controls the kit draws itself -- a tooltip's "?", the "×" that clears a
value or closes a dialog, a drag handle, a row's move and bin buttons, the
password eye, a licence's state, a link field's mark, a gallery file's kind --
are Heroicons outline, named once in Glyphs::DEFAULTS and drawn through
Icons::render(). They carry arraypress-icon like any other icon, so a theme
that restyles one rule restyles them all, and the kit's stylesheet no longer
depends on Dashicons.
use ArrayPress\FieldKit\Icons\Glyphs; echo Glyphs::get( 'close' ); // heroicons-outline:x-mark, 20 by 20 echo Glyphs::get( 'drag', [ 'size' => 16 ] ); // any Icons::render() argument
The script builds some of the same controls (a combobox's clear and chip
buttons, the icon picker's close), and is handed every glyph already drawn as
icons in its configuration -- Glyphs::markup() -- so no path is written
twice. An icon a caller passes, such as a provider's icon, is still drawn as
given: a bare Dashicons name stays the font, with its stylesheet enqueued.
The sets that ship
| Set id | What | Version | Licence | Icons | Size |
|---|---|---|---|---|---|
heroicons-outline |
Heroicons, 24px outline | 2.2.0 | MIT, Tailwind Labs | 324 | 141 KB (26 KB gzipped) |
heroicons-solid |
Heroicons, 24px solid | 2.2.0 | MIT, Tailwind Labs | 324 | 185 KB (38 KB gzipped) |
wordpress |
The block editor's @wordpress/icons |
20.0.0 | GPL-2.0-or-later | 344 | 131 KB (24 KB gzipped) |
dashicons |
Dashicons, read from core's own wp-includes/fonts/dashicons.svg |
core's | GPL-2.0-or-later | 342 | nothing shipped |
Heroicons come from the v2.2.0 release
(optimized/24/outline and optimized/24/solid), with its MIT licence beside
them in assets/icons/heroicons/LICENSE. The WordPress icons come from the
@wordpress/icons 20.0.0 npm package (src/library/*.svg, which the package
now ships as plain SVG files), with Gutenberg's licence in
assets/icons/wordpress/LICENSE.md. Every file was written through the same
cleaning an icon gets before it is printed, by bin/build-icons.php, which is
also how a new release is brought in. Dashicons are not copied: core ships
every glyph as a <symbol> in a sprite, and a Dashicon is read from there as
SVG -- so it draws on a storefront with no icon font loaded. Where the sprite
is missing, the names come from dashicons.css and the icon is drawn as the
font's <span>.
Registering a set
From a theme, or any code that does not know which plugin's copy of the kit it is talking to, use the filter. Every copy of the kit reads it, so the set appears in every plugin's picker:
add_filter( 'arraypress_icon_sets', function ( array $sets ): array { $sets['my-theme'] = [ 'label' => __( 'My theme', 'my-theme' ), 'source' => get_theme_file_path( 'icons' ), // one .svg per icon, named for it 'license' => 'CC BY 4.0 · Jane Doe', 'style' => 'outline', 'keywords' => [ 'basket' => [ 'cart', 'bag', 'shop' ] ], ]; return $sets; } );
From a plugin that has the class, Icons::register( 'my-set', [ ... ] )
does the same for its own copy, and Icons::unregister( 'dashicons' ) takes
one away. source may be a callable returning name => svg markup instead
of a folder; labels names icons whose file names do not read well;
capability (default edit_posts) is what browsing the set over REST
needs; version should change when icons are edited in place (it is worked
out from the names otherwise). An icon font with no SVGs is a set too: give
prefix ('fa fa-'), names and the stylesheet handle that loads it.
Names are lower-case letters, digits, hyphens and underscores; a file whose name is not one is left out.
What is printed
Every icon is somebody else's markup printed into an admin screen, so none
of it is printed as it came. Svg::sanitize() parses it as XML (no network,
no entities -- a DOCTYPE is refused outright) and rebuilds it from an
allow-list of the shapes and presentation attributes an icon is made of.
Scripts, event handlers, <style>, <foreignObject>, links, images,
animation and text are dropped, a href may only point inside the icon,
url() only at the icon's own gradients, and presentation written as style
becomes the attributes it means. Width, height, class and id go -- the size
is set when it is drawn -- and an icon that says neither how to fill nor how
to stroke is given fill="currentColor".
The endpoint
GET /wp-json/field-kit/v1/icons?set=heroicons-outline&search=cart&page=1&per_page=96
(the namespace is this build's: a Strauss-prefixed copy has its own). It
needs a login and the set's capability, answers { set, total, page, pages, icons: [ { value, name, label, svg } ] }, best match first, and is cacheable:
an ETag that answers a repeat with a 304, and Cache-Control: private, max-age=86400. The picker puts the set's version in the URL, so a changed
set is a new address.
Requirements
- PHP 8.3 or later
- WordPress 7.1 or later
License
GPL-2.0-or-later