customization – Prevent posts from being published if the ‘Uncategorized’-category or no category is selected

Question

I do not want a user to be able to publish a post if no category is selected. This exact solution from a similar question is exactly what i want to do:

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;
}

However, the script does not seem to work with WP6 or Gutenberg.

Any solution on how to make the script work in the latest version of WP using Gutenberg and how to enqueue the script in the WP Admin?

0
Joachim 2 months 2022-10-04T12:27:34-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse