Skip to content

Instantly share code, notes, and snippets.

@propertyhive
Last active September 20, 2025 15:48
Show Gist options
  • Save propertyhive/59b14d2a2d7df45e8c5585a433b9f83e to your computer and use it in GitHub Desktop.
Save propertyhive/59b14d2a2d7df45e8c5585a433b9f83e to your computer and use it in GitHub Desktop.
Mandatory reference number field
// Validate before insert/update for the 'property' post type
add_filter('wp_insert_post_data', function ($data, $postarr) {
if (($data['post_type'] ?? '') !== 'property') {
return $data;
}
// Try to read from POST (classic) or meta_input (REST/Gutenberg)
$value = isset($_POST['_reference_number'])
? trim(wp_unslash($_POST['_reference_number']))
: '';
if ($value === '' && isset($postarr['meta_input']['_reference_number'])) {
$value = trim((string) $postarr['meta_input']['_reference_number']);
}
$is_valid = (bool) preg_match('/^[A-Za-z0-9\-]{4,8}$/', $value);
if ($data['post_status'] === 'publish' && !$is_valid) {
//$data['post_status'] = 'draft'; // block publish
add_filter('redirect_post_location', function ($location) {
return add_query_arg('reference_error', 1, $location);
});
}
return $data;
}, 10, 2);
// Show an error message after redirect
add_action('admin_notices', function () {
if (isset($_GET['reference_error'])) {
echo '<div class="notice notice-error"><p><strong>Reference Number</strong> is required and must match <code>[A-Za-z0-9\-]{4,8}</code>.</p></div>';
}
});
add_action('admin_enqueue_scripts', function($hook){
if (!in_array($hook, ['post.php','post-new.php'], true)) return;
$screen = get_current_screen();
if (!$screen || $screen->post_type !== 'property') return;
wp_add_inline_script('jquery-core', "
jQuery(function($){
var form = $('#post');
form.on('submit', function(e){
var field = $('#_reference_number');
if (!field.length) return; // nothing to validate
var val = $.trim(field.val() || '');
var ok = /^[A-Za-z0-9\\-]{4,8}$/.test(val);
if (!ok){
e.preventDefault();
alert('Reference Number is required and must match [A-Za-z0-9-]{4,8}.');
field.focus();
}
});
});
");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment