# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Content](https://wpide.com/library/category/content/)
- Tags: excerpts, publishing, automation
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/content-store-auto-excerpt/

## Code

```php
// 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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Save an Excerpt Automatically When One Is Missing" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
