Generators auto-populate field values on first render when the current value is empty. They are useful for assigning unique identifiers, timestamps, or other computed values to new entries.
A generator runs once when a field is first displayed and its value is falsy (empty string, null, undefined, false, or 0). If the field already has a value, the generator does not run.
Add the generator property to any field definition:
'unique_id' => array(
'type' => 'text',
'label' => 'Unique ID',
'generator' => 'uuid',
'disabled' => true,
),Or with the Field Factory:
$f = wpify_custom_fields()->field_factory;
'unique_id' => $f->text(
label: 'Unique ID',
generator: 'uuid',
disabled: true,
),The uuid generator creates a random UUID v4 string.
'order_token' => array(
'type' => 'text',
'label' => 'Order Token',
'generator' => 'uuid',
),This produces a value like 550e8400-e29b-41d4-a716-446655440000.
- When a field component mounts, the
Fieldcomponent checks ifvalueis falsy andgeneratoris a string. - It applies the WordPress filter
wpifycf_generator_{name}, passing the current value and field props. - If the filter returns a new value different from the current one,
onChangeis called to update the field.
// Simplified internal logic
useEffect(() => {
if (!value && typeof generator === 'string') {
const nextValue = applyFilters('wpifycf_generator_' + generator, value, props);
if (nextValue && nextValue !== value) {
props.onChange(nextValue);
}
}
}, [value, generator]);Register a custom generator by adding a JavaScript filter with the wpifycf_generator_{name} hook:
import { addFilter } from '@wordpress/hooks';
// Generator that creates a timestamp-based ID
addFilter( 'wpifycf_generator_timestamp_id', 'my-plugin', ( value, props ) => {
return value || 'id_' + Date.now().toString( 36 );
} );Then use it in your field definition:
'entry_id' => array(
'type' => 'text',
'label' => 'Entry ID',
'generator' => 'timestamp_id',
),import { addFilter } from '@wordpress/hooks';
addFilter( 'wpifycf_generator_slug', 'my-plugin', ( value, props ) => {
if ( value ) {
return value;
}
// Generate a random slug
return Math.random().toString( 36 ).substring( 2, 10 );
} );- Always check the existing value in your generator filter. Return the existing value if it is truthy to avoid overwriting user data.
- Combine with
disabled: truefor immutable identifiers that should not be edited after generation. - Use with hidden fields when you need auto-generated values that users should not see.
- Generators run client-side only. They execute in the browser when the field renders. They do not run during PHP processing or REST API calls.