Add Missing Labels to Form Fields From Their Placeholder
Finds form fields on the page that have a placeholder but no label or accessible name and gives them one from the placeholder text, a common problem with theme and plugin forms.
Opens WPIDE on
Code
<script>
(function () {
function fix(root) {
root.querySelectorAll('input[placeholder], textarea[placeholder], select[data-placeholder]').forEach(function (field) {
if (field.type === 'hidden' || field.getAttribute('aria-label') || field.getAttribute('aria-labelledby')) { return; }
if (field.id && document.querySelector('label[for="' + CSS.escape(field.id) + '"]')) { return; }
if (field.closest('label')) { return; }
field.setAttribute('aria-label', field.getAttribute('placeholder') || field.getAttribute('data-placeholder'));
});
}
fix(document);
if ('MutationObserver' in window) {
new MutationObserver(function (records) {
records.forEach(function (r) { r.addedNodes.forEach(function (n) { if (n.nodeType === 1) { fix(n); } }); });
}).observe(document.body, { childList: true, subtree: true });
}
})();
</script>
Notes
A visible label is always better; use this as a safety net while you fix the forms themselves.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.