Skip to content

Snippets / PHP

PHP

Custom Form Field Requirement Indicators & Character Counter Styling

B brindeau.joachim · 200 views · Updated 1 year ago
This snippet enhances form field requirement indicators by:

Hiding all "Optional" field indicators
Styling required field indicators with a light red background (#8B0F0F1A) and red text (#8B0F0F)
Styling character counters with a light green background (#0666351A) and green text (#066635)
Simply add this snippet to your theme's functions.php or use a code snippet plugin. No configuration needed - it works automatically with existing form fields. 
add_action('wp_head', 'custom_field_requirement_styles');
function custom_field_requirement_styles() {
?>

/* Style all required indicators first (excluding char counter) */
.ts-form-group .is-required:not(.ts-char-counter),
.ts-file-upload .is-required:not(.ts-char-counter),
span.is-required:not(.ts-char-counter) {
background-color: #8B0F0F1A !important;
color: #8B0F0F !important;
padding: 2px 10px !important;
display: inline-block !important;
border-radius: 4px !important;
}

/* Style character counter */
.ts-char-counter {
background-color: #0666351A !important;
color: #066635 !important;
padding: 2px 10px !important;
display: inline-block !important;
border-radius: 4px !important;
}

/* Hide only those marked as optional */
.is-required[data-optional="true"]:not(.ts-char-counter) {
display: none !important;
visibility: hidden !important;
opacity: 0 !important;
width: 0 !important;
height: 0 !important;
overflow: hidden !important;
margin: 0 !important;
padding: 0 !important;
}

<?php
}

add_action('wp_footer', 'custom_field_requirement_script');
function custom_field_requirement_script() {
?>

document.addEventListener('DOMContentLoaded', function() {
function handleRequirementLabels() {
const requirementSpans = document.querySelectorAll('.is-required:not(.ts-char-counter)');
requirementSpans.forEach(span => {
if (span.textContent.includes('Optional')) {
span.setAttribute('data-optional', 'true');
} else {
span.removeAttribute('data-optional');
}
});
}

// Initial call
handleRequirementLabels();

// Observer for dynamic content
const observer = new MutationObserver(function(mutations) {
handleRequirementLabels();
});

// Start observing
observer.observe(document.body, { 
childList: true, 
subtree: true 
});
});

<?php
}
PHP · 72 lines

Discussion 1

Ask a question or share how you used this.

Log in to join the discussion.
superbadmake 1 year ago

Thank you! 👏

Voxel Guide assistant
Ask about snippets, addons & how-tos

Hey — how can I help?

I can dig through the library for snippets, addons, and tutorials.

AI can be wrong — double-check anything important.