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?

Note: "uncategorized" should not be chosen as well.

  • Maybe you can get inspiration here – JMau Jan 2 '14 at 9:58

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.

| improve this answer | |
  • 1
    Though, I run a jQuery("form[name=post]").submit(handler); – Prakash Raman Jan 2 '14 at 18:18
  • not anymore #publish with wp5 and Guttenberg :/ – Fanky Oct 24 '19 at 16:25

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

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)) {
            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;
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.