I would like to require a featured image on a site I am developing.
I tried the code here: Make featured image required and nothing happened – the JS showed up in the site header, but I could still save the post without a featured image, and never got an error message.
There are several plugins that do this, such as Mandatory Field and WyPiekacz, but I need to do something more complicated… I have a custom meta box with radio buttons. I need to require a featured image only if a certain radio button is checked. I’m already requiring some other fields (category and some custom taxonomies) if certain radio buttons are checked, using jQuery validation.
So I guess I can boil this down to two questions:
-
What’s a good way to require a featured image?
-
How can I integrate that into some existing validation and require a featured image only if a radio button is selected?
Question 1 is probably much easier to answer, and if someone can answer #1, then I can probably figure out #2 on my own.
I would do this by hooking into the
save_post
action, not by javascript.The main idea is to check if both values are there (Your Radiobutton is selected AND the
post_thumbnail
is present), and set the post to draft if they are not, as well as displaying an Information if the user does not fulfill the requirements.First, hook into the
save_post
action, and check if the Radiobutton has your Value, as well as the Post Thumbnail is selected. If everything is okay, you do not need to do anything else, but in your special case you have to prevent the post from being published, as well as display an Error message to inform the user.Here’s what I ended up doing:
Like I said in my comment to fischi, I would generally prefer to use a PHP method like his, but in this case, my site relies on a lot of jQuery validation anyway, so it made sense to just stick with a JavaScript method. This is working just fine for me.