这可能与您正在寻找的内容类似,它不强制设置类别,但不允许用户提交新帖子,除非至少选择了一个类别
此解决方案需要jQuery,但只需稍加修改即可移植到普通JavaScript
//intercept the "update" or "publish" button
$("#post").submit(function(e){
//grab the GET query (just to be sure we are editing a post, not a page)
var split = location.search.replace(\'?\', \'\').split(\'&\').map(function(val){
return val.split(\'=\');
});
//check GET value for "post" and "edit" variables
if(split[0][0] == \'post\' && split[1][0] == \'action\' && split[1][1] == \'edit\' ){
//get the category checkboxes
var categories = $(\'input[name=post_category\\\\[\\\\]]\');
//flag to check if at least one category is selected
var atLeastOneChecked = false;
//iterate over the category checkboxes
for (var i = 0; i < categories.length; i++) {
//if we find one selected and is not the 0 cat let return true and have
//the form submitted
if(categories[i].checked == true && !(categories[i].value == 0)){
return true;
}
}
//else, let your users know they must select a category
alert("You Must Select at least one of your visible categories");
return false;
}
return true;
});