This function shortens the text to a specified number of words and returns the shortened text.
<?php echo wp_trim_words( get_the_content(), 40, '...' ); ?>
In the above example we are passing the post content to the function. It will restrict the length of the content to 40 words and will trim rest of the words.