Take excerpt of the content of the post and send it as the title to create new post

I have written a small plugin exactly for that some time ago. It hooks into 'save_post' and takes the first 20 characters as title if there is no title set already:

add_action( 'save_post', 't5_fix_empty_title', 11, 2 );

/**
 * Fills an empty post title from the first words of the post.
 *
 * @param  int    $post_id      Post ID
 * @param  object $post         Post object
 * @return void
 */
function t5_fix_empty_title( $post_id, $post )
{
    if ( ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
        or ! current_user_can( 'edit_post', $post_id )
        or ! empty ( $post->post_title )
        or empty ( $post->post_content )
        or wp_is_post_revision( $post )
    )
    { // Noting to do.
        return;
    }

    // Remove all tags and replace breaks whith white space.
    $no_tags = wp_strip_all_tags( $post->post_content, TRUE );

    // The post content contains just markup.
    if ( '' === $no_tags )
    {
        return;
    }

    $length = apply_filters( 't5_fix_empty_title_length', 20 );
    $words  = preg_split( "/\s+/", $no_tags, $length, PREG_SPLIT_NO_EMPTY );
    array_pop( $words );

    $title = implode( ' ', $words );
    // Add a no break space and an ellipsis at the end.
    $title = rtrim( $title, '.,!?…*' ) . ' …';

    wp_update_post( array ( 'ID' => $post_id, 'post_title' => $title ) );
}

Leave a Comment