Require an Excerpt Before Publishing
Blocks publishing posts that have no hand-written excerpt, so archive pages, search results and social shares always have a proper summary.
Opens WPIDE on
Code
// Minimum excerpt length in characters.
$wpide_excerpt_min_chars = 50;
// Post types that need an excerpt.
$wpide_excerpt_types = array( 'post' );
add_filter( 'rest_pre_insert_post', function ( $prepared, $request ) use ( $wpide_excerpt_min_chars, $wpide_excerpt_types ) {
$post_id = (int) ( $prepared->ID ?? 0 );
$type = $post_id ? get_post_type( $post_id ) : 'post';
$status = $request->get_param( 'status' ) ? $request->get_param( 'status' ) : get_post_status( $post_id );
if ( ! in_array( $type, $wpide_excerpt_types, true ) || ! in_array( $status, array( 'publish', 'future' ), true ) ) {
return $prepared;
}
$excerpt = null !== $request->get_param( 'excerpt' ) ? $request->get_param( 'excerpt' ) : get_post_field( 'post_excerpt', $post_id, 'raw' );
$excerpt = is_array( $excerpt ) ? ( $excerpt['raw'] ?? '' ) : (string) $excerpt;
if ( mb_strlen( trim( wp_strip_all_tags( $excerpt ) ) ) < $wpide_excerpt_min_chars ) {
return new WP_Error( 'wpide_excerpt_required', sprintf( 'Please write an excerpt of at least %d characters before publishing.', $wpide_excerpt_min_chars ), array( 'status' => 400 ) );
}
return $prepared;
}, 10, 2 );
Notes
Set $wpide_excerpt_min_chars to require a minimum length; drafts can still be saved.
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.