Require a Real Category Before Publishing
Stops posts from being published while they are only in "Uncategorized" or have no category, and shows the writer a clear message in the block or classic editor.
Opens WPIDE on
Code
$wpide_has_real_category = function ( $category_ids ) {
$category_ids = array_filter( array_map( 'absint', (array) $category_ids ) );
return (bool) array_diff( $category_ids, array( (int) get_option( 'default_category' ) ) );
};
// Block editor and REST API.
add_filter( 'rest_pre_insert_post', function ( $prepared, $request ) use ( $wpide_has_real_category ) {
$status = $request->get_param( 'status' ) ? $request->get_param( 'status' ) : get_post_status( $prepared->ID ?? 0 );
if ( ! in_array( $status, array( 'publish', 'future' ), true ) ) {
return $prepared;
}
$categories = null !== $request->get_param( 'categories' ) ? $request->get_param( 'categories' ) : wp_get_post_categories( (int) ( $prepared->ID ?? 0 ) );
if ( ! $wpide_has_real_category( $categories ) ) {
return new WP_Error( 'wpide_category_required', 'Please choose a category other than "Uncategorized" before publishing.', array( 'status' => 400 ) );
}
return $prepared;
}, 10, 2 );
// Classic editor.
add_filter( 'wp_insert_post_data', function ( $data, $postarr ) use ( $wpide_has_real_category ) {
if ( 'post' !== $data['post_type'] || ! in_array( $data['post_status'], array( 'publish', 'future' ), true ) || ! isset( $_POST['post_category'] ) || wp_is_serving_rest_request() ) {
return $data;
}
if ( ! $wpide_has_real_category( wp_unslash( $_POST['post_category'] ) ) ) {
$data['post_status'] = 'draft';
set_transient( 'wpide_category_notice_' . get_current_user_id(), 1, 60 );
}
return $data;
}, 10, 2 );
add_action( 'admin_notices', function () {
if ( get_transient( 'wpide_category_notice_' . get_current_user_id() ) ) {
delete_transient( 'wpide_category_notice_' . get_current_user_id() );
echo '<div class="notice notice-error"><p>The post was saved as a draft: choose a category other than "Uncategorized" to publish it.</p></div>';
}
} );
Notes
Drafts can still be saved; only publishing and scheduling are blocked.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.