Save an Excerpt Automatically When One Is Missing
Fills in the excerpt field from the first sentences of the post when it is saved without one, so feeds, plugins and APIs that read the stored excerpt always get a summary.
Opens WPIDE on
Code
// Length of the generated excerpt.
$wpide_auto_excerpt_words = 35;
// Post types to fill.
$wpide_auto_excerpt_types = array( 'post' );
add_filter( 'wp_insert_post_data', function ( $data ) use ( $wpide_auto_excerpt_words, $wpide_auto_excerpt_types ) {
if ( '' !== trim( $data['post_excerpt'] ) || ! in_array( $data['post_type'], $wpide_auto_excerpt_types, true ) || ! in_array( $data['post_status'], array( 'publish', 'future', 'pending' ), true ) ) {
return $data;
}
$content = wp_unslash( $data['post_content'] );
$content = excerpt_remove_blocks( strip_shortcodes( $content ) );
// Skip headings so the summary starts with real text.
$content = preg_replace( '#<h[1-6][^>]*>.*?</h[1-6]>#is', '', $content );
$text = trim( preg_replace( '/\s+/', ' ', wp_strip_all_tags( $content ) ) );
if ( '' !== $text ) {
$data['post_excerpt'] = wp_slash( wp_trim_words( $text, $wpide_auto_excerpt_words, '...' ) );
}
return $data;
} );
Notes
Writers can still type their own excerpt, which is never overwritten; change $wpide_auto_excerpt_words for a longer summary.
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.