Halloween Sale 15% off Ends in See the plans
PHP

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.

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

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

  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.