Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

Thank-you.

share|improve this question
1  
You can either fill it with a default value, or check if the field is empty, maybe provide the user a notice on that, and don't allow for/apply the default functionality. But maybe you could get a more detailed and useful answer if you provided more information...? –  t f Apr 22 '13 at 17:23
add comment

2 Answers

up vote 4 down vote accepted

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.

share|improve this answer
add comment

There is no way to require input per PHP. Only the browser can do that, and the browser gets the output after PHP is done.

You can add the attribute required:

<input name=foo required>

But not all browsers support that, and you have to check the value still in your validation handler.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.