Skip to content

[00] Subset Fill, For developers

Developer reference

Last updated

The hooks that shape what the builder sends and returns, adding a field type, a provider or a content source, the WP-CLI command, and Pro's filters.

This page lists Subset Fill’s public hooks and classes, with examples. The hook prefix is sfcb_ (Pro uses sfcb_pro_) and the PHP namespace is FunctionForm\FlexibleContentBuilder. Hook names, parameters and meaning don’t change within a major version.

Whatever a filter changes, the answer is still checked word for word against the pasted content and sanitized before it reaches the editor. There’s no hook that saves a post or turns that check off.

Hooks

Builds

HookTypeWhen
sfcb_builder_schemafilterAfter the field is read into a JSON Schema, on every build request
sfcb_builder_field_handlersfilterWhen the field type handlers are built
sfcb_builder_promptfilterBefore each chunk is sent to the provider
sfcb_builder_resultfilterWhen a chunk’s rows come back, before validation
sfcb_sanitize_valuefilterWhen a value of a field type the builder doesn’t know is sanitized
sfcb_build_responsefilterBefore each build response is returned to the browser
sfcb_builder_completedactionWhen the last chunk of a build has been arranged
sfcb:builder-completedJS eventIn the browser, after the rows are in the field
sfcb.fillFieldJS filterBefore the builder fills a field in the editor
sfcb_chunk_wordsfilterWords per chunk (default 1,500)
sfcb_max_content_bytesfilterLargest paste accepted (default 500 KB)
sfcb_rate_limitfilterBuild requests per user per hour (default 60)

Providers

HookTypeWhen
sfcb_register_providersactionAfter the built-in providers register. Passes the ProviderRegistry.
sfcb_provider_timeoutfilterSeconds before a provider request times out (default 120)
sfcb_quota_fallbackfilterWhen the chosen provider is out of credit. Return another provider’s ID.
sfcb_quota_fallback_usedactionWhen a request is retried on the fallback provider

Add-ons, admin screen and Build box

HookTypeWhen
sfcb_loadingactionAt the start of the plugin’s load, before any component registers. Passes the Plugin.
sfcb_admin_tabsfilterWhen the tabs on Subset → Fill are built
sfcb_admin_panel_{slug}actionTo print an added tab’s panel (administrators only)
sfcb_admin_enqueue_{slug}actionOn an added tab, to enqueue its scripts and styles
sfcb_admin_settings_panelactionAt the end of the Settings tab, after the form
sfcb_settings_after_formactionAfter the settings form. Kept for older add-ons; use the hooks above.
sfcb_editor_enqueuedactionAfter the editor script (sfcb-editor) is enqueued on a post edit screen
sfcb/content_sourcesJS filterWhen the Build box opens, to add content sources

Change the schema

sfcb_builder_schema filters the JSON Schema the AI must follow. The answer is validated against the same schema, so a change here changes both what’s asked for and what’s accepted.

apply_filters( 'sfcb_builder_schema', array $json_schema, array $field ): array

The schema is a rows array whose items are an anyOf with one object per layout. Each layout object has properties.layout (an enum of one name) and properties.fields. $field is the Flexible Content field from acf_get_field().

<?php
add_filter(
	'sfcb_builder_schema',
	function ( array $schema, array $field ): array {
		foreach ( $schema['properties']['rows']['items']['anyOf'] as &$layout ) {
			if ( 'testimonial' === $layout['properties']['layout']['enum'][0] ) {
				$layout['description'] .= ' Quotes only, never paraphrased.';
			}
		}
		return $schema;
	},
	10,
	2
);

Keep it valid for strict structured output: every property listed in required, additionalProperties false, and null allowed wherever the source may have nothing to put.

Add a field type

The built-in handlers cover text, textarea, email, URL, select, radio, checkbox, button group, WYSIWYG, number, true/false, link, image, group and repeater. A field of any other type is left out and reported to the editor as unsupported until you add a handler.

apply_filters( 'sfcb_builder_field_handlers', array $handlers ): array

$handlers is keyed by ACF field type. Add a type, or replace a built-in one by using its key. A handler implements Schema\FieldHandler and returns the JSON Schema of the field’s value, which should allow null. Group-like handlers call $builder->fields_object( $field['sub_fields'], $path ) for their sub-fields.

For a type the builder doesn’t know, you sanitize the value with sfcb_sanitize_value:

apply_filters( 'sfcb_sanitize_value', mixed $sanitized, mixed $value, array $field, string $path, Sanitizer $sanitizer ): mixed

$sanitized starts as null, which leaves the field empty. In the editor, the value is set with acf.val() on the field’s input.

<?php
use FunctionForm\FlexibleContentBuilder\Schema\FieldHandler;
use FunctionForm\FlexibleContentBuilder\Schema\SchemaBuilder;

final class Color_Handler implements FieldHandler {
	public function schema( array $field, SchemaBuilder $builder, string $path ): array {
		return array(
			'type'        => array( 'string', 'null' ),
			'description' => 'A hex color such as #1a2b3c, only if the source gives one.',
			'pattern'     => '^#[0-9a-fA-F]{6}$',
		);
	}
}

add_filter( 'sfcb_builder_field_handlers', function ( array $handlers ): array {
	$handlers['color_picker'] = new Color_Handler();
	return $handlers;
} );

add_filter(
	'sfcb_sanitize_value',
	function ( $sanitized, $value, array $field ) {
		return 'color_picker' === $field['type'] ? sanitize_hex_color( (string) $value ) : $sanitized;
	},
	10,
	3
);

These SchemaBuilder methods are public for handlers:

MethodUse
fields_object()Schema for a list of sub-fields (groups, repeaters, clones)
layout_schema()Schema for a row of a nested Flexible Content layout, with its description and limits
item_limits()A field’s row or item limits
depth()The nesting level of the fields being read. The root is 1, a field in a top-level layout sees 3.
build_id()Changes on every build, for a handler that keeps a budget

Return an empty array from schema() to leave the field out and report it as unsupported. That’s how a handler stops at a depth limit.

For sfcb_sanitize_value callbacks on nested fields, Validation\Validator checks a value whose schema is an anyOf of row objects against the variant its layout names, and Validation\Sanitizer::fields() sanitizes a list of sub-fields.

Change the prompt

sfcb_builder_prompt filters the part of each request that describes the layouts and carries the content. The fixed rules in the system prompt (copy word for word, never invent) can’t be filtered.

apply_filters( 'sfcb_builder_prompt', string $prompt, Schema $schema, int $index, int $total ): string

$index is the chunk’s position from 0 and $total is the number of chunks. Returning an empty or non-string value keeps the original prompt.

<?php
add_filter(
	'sfcb_builder_prompt',
	function ( string $prompt, $schema, int $index ): string {
		return 0 === $index ? $prompt . "\n\nThis page is a press release." : $prompt;
	},
	10,
	3
);

Change the result

sfcb_builder_result gets each chunk’s rows before validation, so anything you add that isn’t in the source is cleared like any other invented text.

apply_filters( 'sfcb_builder_result', array $rows, array $field, int $post_id, int $chunk ): array
<?php
// Never start a page with a call to action.
add_filter(
	'sfcb_builder_result',
	function ( array $rows, array $field, int $post_id, int $chunk ): array {
		return ( 0 === $chunk && 'cta' === ( $rows[0]['layout'] ?? '' ) ) ? array_slice( $rows, 1 ) : $rows;
	},
	10,
	4
);

sfcb_build_response filters the whole response for each chunk before it’s returned, so you can add flags and your own keys:

apply_filters( 'sfcb_build_response', array $data, array $field, Schema $schema, int $post_id, bool $done ): array

Leave rows as the model returned them, because the browser sends them back with the next chunk to be validated again. The rows are final only when $done is true.

After a build

sfcb_builder_completed fires with the final rows, the field, the post ID and a summary: flags, dropped, unplaced, chunks, provider, model and usage (input_tokens, output_tokens).

<?php
add_action(
	'sfcb_builder_completed',
	function ( array $rows, array $field, int $post_id, array $summary ) {
		error_log( sprintf( 'Built %d rows for post %d with %s.', count( $rows ), $post_id, $summary['provider'] ) );
	},
	10,
	4
);

In the browser, sfcb:builder-completed bubbles from the field once the rows are in place. event.detail has rows, flags, dropped, unplaced, field (the field key), mode (append or replace) and the rest of the last response.

document.addEventListener("sfcb:builder-completed", (event) => {
  console.log(`Built ${event.detail.rows.length} rows into ${event.detail.field}`);
});

Nothing is saved at either point. The editor can still undo the build or leave the page.

Fill a field in the editor

The sfcb.fillField filter (wp.hooks) lets your script fill a field before the builder does. Return true when you’ve handled it. Enqueue your script with sfcb-editor as a dependency.

wp.hooks.addFilter("sfcb.fillField", "my-plugin", (handled, args) => {
  if (handled || args.type !== "color_picker") return handled;
  args.field.val(args.value);
  return true;
});

args has the field model (field), type, value, path, valuePath, flag, flags, context (with result, row and attention) and the helpers fill, subFields, addRow, note and layoutIsFull.

Add a provider

A provider is a class implementing Providers\Provider, registered on sfcb_register_providers. It then appears in the Provider list on Subset → Fill.

<?php
add_action( 'sfcb_register_providers', function ( $registry ): void {
	$registry->register( new My_Local_Provider() );
} );

ProviderRegistry has defaults(), register(), get(), available() and configured_providers(). The last returns the IDs of available providers that need a key and have a usable one, in registration order.

A provider that bills in its own units can also implement Providers\ReportsUsage:

  • balance_note(): string prints in a Credits row on the settings screen while the provider is selected. It allows <a href>, <code> and <strong>.
  • estimate_note( int $characters, int $chunks ): string shows under the paste area of the Build box and refreshes as the editor types.

Neither is cached for you, so cache anything that needs an HTTP request.

Out of credit

A provider with no credit left returns a WP_Error with the code ProviderError::QUOTA (sfcb_provider_quota). By default the editor sees the error. Return another provider’s ID from sfcb_quota_fallback to retry the request there, with that provider’s saved model and key. Later parts of the same build go straight to the fallback.

apply_filters( 'sfcb_quota_fallback', string $provider_id, Provider $failed, WP_Error $error ): string
do_action( 'sfcb_quota_fallback_used', Provider $from, Provider $to, WP_Error $error )

Add a tab to the settings screen

sfcb_admin_tabs adds tabs to Subset → Fill, between Settings and About. Return slug => label. The tab opens at admin.php?page=sfcb-settings&tab={slug}.

<?php
add_filter( 'sfcb_admin_tabs', function ( array $tabs ): array {
	$tabs['reports'] = __( 'Reports', 'my-plugin' );
	return $tabs;
} );

add_action( 'sfcb_admin_panel_reports', function (): void {
	echo '<p>Your panel.</p>';
} );

Slugs go through sanitize_key(). Empty slugs, settings, about and empty labels are dropped. Use sfcb_admin_enqueue_{slug} for the tab’s assets, and sfcb_admin_settings_panel to add a section under the provider settings.

Add a content source

A content source adds a choice to Content from in the Build box, such as a file or a URL. It produces HTML, which goes through the same build as pasted content. Your source brings its own REST route and permission checks, sanitizes what it returns with wp_kses_post(), and doesn’t keep the content after the request.

<?php
add_action( 'sfcb_editor_enqueued', function ( string $handle ): void {
	wp_enqueue_script( 'my-addon-sources', plugins_url( 'sources.js', __FILE__ ), array( $handle ), '1.0', true );
} );
acf.addFilter("sfcb/content_sources", (sources, { field, postId }) =>
  sources.concat({
    id: "word", // letters, digits, - and _. "paste" is taken.
    label: "Word file",
    mount(panel, api) {
      // Draw controls in `panel`. `api` has postId, fieldKey, notify(type, text) and status(text).
      return {
        async getContent({ signal }) {
          return html; // or throw with a readable message
        },
        focus() {}, // optional
        destroy() {}, // optional
      };
    },
  }),
);

Sources that are malformed, reuse an ID or throw in mount() are skipped.

Load order for add-ons

  1. Your add-on’s main file adds an action on sfcb_loading and nothing else.
  2. On plugins_loaded, the plugin fires sfcb_loading with the Plugin. Check FunctionForm\FlexibleContentBuilder\VERSION there and add your other hooks.
  3. On acf/init, the components register and sfcb_register_providers fires.

Don’t call the plugin’s services from the sfcb_loading callback itself, only from hooks it adds.

Public API

An add-on may rely on these and nothing else:

  • The hooks on this page and the VERSION constant.
  • Providers\ProviderRegistry and its methods listed above.
  • Schema\FieldHandler, Schema\HandlerRegistry::register() and the SchemaBuilder methods listed above.
  • Validation\Validator and Validation\Sanitizer::fields(), for sfcb_sanitize_value callbacks.
  • The provider types: Providers\Provider, Providers\ReportsUsage, Providers\Connection, Providers\StructuredRequest, Providers\StructuredResult and the Providers\ProviderError codes.

Everything else is internal and can change in any release, including settings, REST controllers, the engine and the admin screens. Within a major version, the public API keeps its names, signatures and meaning. New methods and new ProviderError codes can arrive in a minor release.

Constants

ConstantUse
SFCB_ANTHROPIC_API_KEYAnthropic key. Takes precedence over the settings screen.
SFCB_OPENAI_API_KEYOpenAI key
SFCB_OPENROUTER_API_KEYOpenRouter key

REST endpoint

POST /sfcb/v1/build takes post_id, field_key, content, chunk and rows, and arranges one chunk per request. It needs edit_post on the post, and the field must have the builder on. Over the rate limit it returns 429 with Retry-After. Over the content limit it returns 413.

WP-CLI

wp subset content-builder map runs a file through your provider and prints the rows as JSON after the word-for-word check. Nothing is saved. WP-CLI commands lists it with the provider and key commands, and Pro’s import.

Pro filters

FilterDefaultWhat it changes
sfcb_pro_max_schema_depth10Deepest object nesting in a schema, for nested fields
sfcb_pro_max_nested_flexible6Most nested Flexible Content fields in one build
sfcb_pro_docx_max_bytes10 MBLargest Word file accepted
sfcb_pro_url_import_max_bytes3 MBLargest page fetched from a web address
sfcb_pro_url_import_timeout10Seconds before a web address fetch times out
sfcb_pro_url_import_pre_fetchnull( ?string $html, string $url ). Return HTML to use instead of fetching the page.
sfcb_pro_url_import_html( string $html, string $url ). The extracted HTML, before it’s sanitized.
sfcb_pro_hosted_fallback_providerWhich of your own providers takes over when credits run out
sfcb_pro_buy_credits_urlThe Buy more link
sfcb_pro_api_urlWhere hosted credits requests go. Or define SFCB_PRO_API_URL.
sfcb_pro_hosted_site_urlThe site address sent with hosted builds
sfcb_pro_hosted_instance_idThe installation ID sent with hosted builds

Get help

Report bugs and request features at subset-feedback (opens in a new tab). For anything else, email hello@subsetwp.com.