Assigning a category to a user role

This may be similar to what you are looking for, it doesn’t force a category, but doesn’t let the user submit the new post unless at least one category is selected

This solution requires jQuery, but with little modification can be ported to plain 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;
});

Leave a Comment