Gravity Forms Custom Validation ( bot check )
add_filter('gform_field_validation', function($result, $value, $form, $field) {
// The field title to check
$target_field_title = 'bot check';
// Check if the field's title matches
if (strtolower($field->label) === strtolower($target_field_title)) {
// Get the current website URL and remove the protocol
$website_url = preg_replace('#^https?://#', '', get_site_url());
// Construct the expected value
$expected_value = $website_url . ' ready';
// Check if the submitted value matches the expected value
if (trim($value) !== $expected_value) {
// Set the validation to false with a custom error message
$result['is_valid'] = false;
$result['message'] = "Bot check failed";
}
}
return $result;
}, 10, 4);
add_action('wp_footer', function() {
?>
<script>
jQuery(document).ready(function($) {
<?php if (!current_user_can('administrator')) : ?>
// Hide "bot check" field immediately for non-admin users
$('.gfield_label').each(function() {
if ($(this).text().trim().toLowerCase() === 'bot check') {
// Hide the field container
$(this).closest('.gfield').css('display', 'none');
}
});
<?php endif; ?>
// Wait 5 seconds and inject the URL and "ready" text into the field
setTimeout(function() {
// Get the website URL without protocol
var siteURL = window.location.hostname;
// Construct the value to inject
var injectedValue = siteURL + " ready";
// Loop through Gravity Form fields to find the one with the title "bot check"
$('.gfield_label').each(function() {
if ($(this).text().trim().toLowerCase() === 'bot check') {
// Find the corresponding input field and set the value
$(this).closest('.gfield').find('input').val(injectedValue);
}
});
}, 5000); // Wait 5 seconds (5000ms)
});
</script>
<?php
});