I’m building a plugin that has a meta box. Some of the fields in the meta box are required. Is using jQuery the only method for achieving this? Can I require that a field is filled in using PHP?
3 Answers
You can use Javascript to create a first-line convenience warning, but that is not a secure solution. You will need to interrupt the post save to truly create a required field.
function req_meta_wpse_96762($data){
$allow_pending = false;
if (isset($_POST['meta'])) {
foreach ($_POST['meta'] as $v) {
if ('your_required_key' === $v['key'] && !empty($v['value'])) {
$allow_pending = true;
}
}
}
if (false === $allow_pending) {
$data['post_status'] = 'draft';
}
return $data;
}
add_action('wp_insert_post_data','req_meta_wpse_96762');
That will also reset the post to ‘Draft’ if the meta field is deleted.