Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.