Prevent post from being published if no category selected

I do not want a user to be able to publish a post if no category is selected. I don’t mind throwing a JS alert or handling this on the server side as well.

Anyway, how can I ensure this?

Read More

Note: “uncategorized” should not be chosen as well.

Related posts

2 comments

  1. You can do this easily with jQuery:

    /* Checks if cat is selected when publish button is clicked */
    jQuery( '#submitdiv' ).on( 'click', '#publish', function( e ) {
        var $checked = jQuery( '#category-all li input:checked' );
    
        //Checks if cat is selected
        if( $checked.length <= 0 ) {
            alert( "Please Select atleast one category" );
            return false;
        } else { 
            return true;
        }
    } );
    

    The above code will show an alert box if no category is selected. You can use dialog box instead if you’d like.

  2. Here is my solution. I include this .js file on all Admin Pages, but since some of my custom post types don’t include categories, I handle that situation by checking and returning true at the beginning of the function. I’m not an expert at JQuery, so I wrote most of this in straight JavaScript. Note that it specifically checks for the unpublished category, as well as checking the number of categories selected.

    jQuery(document).ready(function ($) {
        // Check for exactly one category before publishing or updating
        $('#publish').click(checkForCategory);
    });
    
    function checkForCategory()
    {
        var categoryBlock = document.getElementById('categorychecklist');
        if categoryBlock == null {
            return true;
        }
        var catList = categoryBlock.getElementsByClassName('selectit');
    
        var error = false;
        var idx;
        var selectedCnt = 0;
        var uncategorized = false;
    
        // Iterate through all of the categories to count the checked ones
        for (idx = 0; idx < catList.length; idx++) {
            inputElements = catList[idx].getElementsByTagName('input');
            if ((inputElements.length > 0) && (inputElements[0].checked)) {
                selectedCnt++;
                if (catList[idx].innerHTML.indexOf('Uncategorized') > 0) {
                    uncategorized = true;
                }
            }
        }
    
        if (uncategorized) {
            alert("You must unselect the Uncategorized category before publishing.");
            error = true;
        }
        else if (selectedCnt == 0) {
            alert("You must select a category before publishing.");
            error = true;
        }
        else if (selectedCnt > 1) {
            alert("You may only select one category when publishing.");
            error = true;
        }
    
        return !error;
    }
    

Comments are closed.