Can you make a custom metabox field be required to save a new post?

You can use jQuery as it already loaded on posts. The idea is to stop the form submit action.

I have two html elements in my meta:

<select name="cars" class="required">
  <option value="-1">Choose a car</option>
  <option value="volvo">volvo</option>
  <option value="saab">saab</option>
  <option value="bmw">bmw</option>
</select>

<input type="text" class="required" placeholder="Type year">

The form has an id of “post”. So with jquery we can write:

jQuery(function($){ //make sure DOM is loaded and pass $ for use
    $('#post').submit(function(e){ // the form submit function
         $('.required').each(function(){
           if( $(this).val() == '-1' || $(this).val() == '' ){ // checks if empty or has a predefined string
             //insert error handling here. eg $(this).addClass('error');
             e.preventDefault(); //stop submit event
           }
         })
    });
});

I think that should do it. To add javascript on a post page use admin_init hook and wp_enque_script. search for them in the codex and you will find out how to use them. if not post a new question.

Leave a Comment