Build Your Own Form UI
Use native fetch when the form should use your own markup or design system. WordPress supplies the field list and still validates every submission.
The browser code on this page never holds the API key. It posts to a route on your server, which adds the key.
The Request Flow
- Request
GET /wp-json/core-forms/v1/forms/{id}. - Render inputs from its
fieldslist, keeping eachname. - Post the answers as JSON to your server route.
- The route forwards them to
submit_urlwith theX-Core-Forms-Keyheader. - Show
message.text, highlightfieldor followredirect_url.
This is the whole exchange in server-side JavaScript:
// Runs on your server, where the key stays private.
const base = 'https://cms.example.com/wp-json/core-forms/v1';
const form = await fetch(`${base}/forms/123`).then((response) => response.json());
const response = await fetch(form.submit_url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Core-Forms-Key': process.env.CORE_FORMS_API_KEY,
},
body: JSON.stringify({
name: 'Ada',
email: 'ada@example.com',
topics: ['sales', 'support'],
_cf_page_url: 'https://www.example.com/contact',
}),
});
const result = await response.json();
console.log(response.status, result.message);
Add the Submit Script
Save this as core-forms-client.js in your public folder. The Astro, Next.js, Node.js and PHP guides use the same file.
// Submits Core Forms markup through a route on your own site.
(function () {
function messageText(data, fallback) {
var message = data && data.message;
if (typeof message === 'string' && message) return message;
if (message && typeof message.text === 'string' && message.text) return message.text;
return fallback; // message.text can be an empty string
}
function emit(host, name, detail) {
host.dispatchEvent(new CustomEvent(name, { detail: detail, bubbles: true }));
}
function bind(host) {
if (!host) return;
var form = host.querySelector('form');
if (!form || form.dataset.cfBound) return;
form.dataset.cfBound = '1';
var status = document.createElement('div');
status.className = 'cf-form-status';
status.setAttribute('role', 'status');
status.tabIndex = -1;
host.insertBefore(status, host.firstChild);
var sending = false;
form.addEventListener('submit', async function (event) {
event.preventDefault();
if (sending) return;
status.textContent = '';
emit(host, 'cf:submit', { form: form });
var payload = Object.create(null);
var hasFile = false;
new FormData(form).forEach(function (value, name) {
if (typeof value !== 'string') {
if (value.name) hasFile = true;
return;
}
payload[name] = name in payload ? [].concat(payload[name], value) : value;
});
if (hasFile) {
status.textContent = 'This form cannot send files. Please use the upload link instead.';
return;
}
payload._cf_page_url = window.location.href;
var buttons = form.querySelectorAll('button[type="submit"], input[type="submit"]');
function setBusy(busy) {
sending = busy;
form.setAttribute('aria-busy', String(busy));
buttons.forEach(function (button) { button.disabled = busy; });
}
form.querySelectorAll('[aria-invalid="true"]').forEach(function (field) {
field.removeAttribute('aria-invalid');
});
setBusy(true);
try {
var response = await fetch(host.dataset.submitUrl || '/api/submit', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
body: JSON.stringify(payload),
});
var data = await response.json();
if (!response.ok) {
status.textContent = messageText(data, 'The form could not be sent. Please try again.');
var field = data.field && (form.elements[data.field] || form.elements[data.field + '[]']);
if (field && !field.tagName) field = field[0]; // radio and checkbox groups
if (field) {
field.setAttribute('aria-invalid', 'true');
field.focus();
}
emit(host, 'cf:error', data);
} else {
emit(host, 'cf:success', data);
if (data.redirect_url) {
var target = new URL(data.redirect_url, window.location.href);
if (target.protocol === 'https:' || target.protocol === 'http:') {
window.location.assign(target.href);
return;
}
}
status.textContent = messageText(data, 'Thanks. Your message was sent.');
form.remove();
status.focus();
}
} catch (error) {
status.textContent = 'Network error. Please try again.';
emit(host, 'cf:error', error);
}
setBusy(false);
});
emit(host, 'cf:mounted', null);
}
function init() {
document.querySelectorAll('[data-core-form]').forEach(bind);
}
window.CoreFormsClient = { bind: bind, init: init };
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);
else init();
})();
It does these jobs:
- Binds forms inside
[data-core-form], or any host passed toCoreFormsClient.bind(). - Posts to the host’s
data-submit-url, or/api/submit. - Sends repeated fields as arrays and adds the page URL.
- Blocks a second submission while the first is running.
- Focuses the field the server rejected.
- Fires the same 4 events as the embed.
- Shows messages as plain text.
Render the Fields
Save this example as render-core-form.js. It covers standard inputs and stops on a type it doesn’t know, so no field goes missing unnoticed.
const INPUT_TYPES = [
'text', 'email', 'url', 'tel', 'number', 'date', 'time', 'datetime-local',
'month', 'week', 'search', 'color', 'range', 'hidden',
];
function element(tag, props = {}, children = []) {
const node = Object.assign(document.createElement(tag), props);
node.append(...children);
return node;
}
function renderField(field, id) {
const { name, type, required, label } = field;
const options = field.options ?? [];
if ((type === 'radio' || type === 'checkbox') && options.length) {
const inputName = type === 'checkbox' ? `${name}[]` : name;
const choices = options.map((option) => element('label', {}, [
element('input', {
type,
name: inputName,
value: option.value,
required: type === 'radio' && required,
}),
` ${option.label}`,
]));
return element('fieldset', {}, [element('legend', { textContent: label }), ...choices]);
}
if (type === 'checkbox') {
const box = element('input', { type, name, id, value: '1', required });
return element('label', { htmlFor: id }, [box, ` ${label}`]);
}
let control;
if (type === 'textarea') {
control = element('textarea', { name, id, required });
} else if (type === 'select') {
control = element('select', { name, id, required }, [
element('option', { value: '', textContent: 'Choose one' }),
...options
.filter((option) => option.value !== '')
.map((option) => element('option', { value: option.value, textContent: option.label })),
]);
} else if (INPUT_TYPES.includes(type)) {
control = element('input', { type, name, id, required });
} else {
throw new Error(`Add a component for the "${type}" field "${name}".`);
}
if (type === 'hidden') return control;
return element('p', {}, [element('label', { htmlFor: id, textContent: label }), control]);
}
export async function renderCoreForm(host, schemaUrl) {
const response = await fetch(schemaUrl);
if (!response.ok) throw new Error(`Form request returned ${response.status}.`);
const schema = await response.json();
const fields = schema.fields
.filter((field) => !['submit', 'button', 'reset'].includes(field.type))
.map((field, index) => renderField(field, `form-${schema.id}-${index}`));
host.replaceChildren(element('form', { className: 'cf-form', method: 'post' }, [
...fields,
element('button', { type: 'submit', textContent: 'Send' }),
]));
window.CoreFormsClient.bind(host);
}
Use it on a page:
<div id="contact" data-submit-url="/api/submit"></div>
<script src="/core-forms-client.js" defer></script>
<script type="module">
import { renderCoreForm } from '/render-core-form.js';
const host = document.querySelector('#contact');
renderCoreForm(host, 'https://cms.example.com/wp-json/core-forms/v1/forms/123')
.catch(() => {
host.textContent = 'The form could not load. Please try again later.';
});
</script>
A browser request for the schema needs your front end in Allowed origins. You can also fetch the schema on your server and pass it to the page.
Field Rules
- Keep field names unchanged. Unknown keys aren’t stored.
- Send an array for checkbox groups.
topicsandtopics[]both work. - For radio buttons, selects and checkboxes, send the option’s
value, not its label. - Check the value of a single checkbox in the form’s markup if it isn’t
1. - Send files as multipart straight from your server. The submit script and proxy starters on these pages handle text fields only.
- Leave an empty file field out of JSON.
Object.fromEntries(new FormData(form))turns it into{}, which is refused. - The honeypot is optional with your own markup. If you send
_cf_hfollowed by the form ID, keep it empty. - Add
_cf_page_urlto fill[CF_REFERRER_URL].
Conditional display, steps and live calculations belong to your components. WordPress still checks conditional required fields.
The schema’s captcha key lists the captchas the form checks, with their public site keys. If it lists Turnstile, put this element inside the form and load the captcha script:
<div class="cf-turnstile-container" data-sitekey="YOUR_TURNSTILE_SITE_KEY"></div>