• Resolved Jonathan Stegall

    (@jonathanstegall)


    So, hello.

    At the moment I use the Evermore plugin to automatically create excerpts of posts on the home page of a blog I’m managing. It makes an excerpt out of the first paragraph. I’m loving it for the first, most recent post.

    What I want to achieve, though, is a smaller excerpt for the other recent posts that appear on the home page. If possible, I want these posts to automatically have an excerpt that is the first sentence. So, theoretically, a plugin could stop the post after the first occurrence of a period, and with few exceptions this would be perfect. Is there a plugin that does this? Or, maybe a function someone has seen that can be added to a theme?

    Thanks so much for any ideas.
    Jonathan

Viewing 2 replies - 1 through 2 (of 2 total)
  • Since you’re comfortable with the “few exceptions” this may lead to, here’s something nearly off the top of my head. Just replace the_content() or the_excerpt() (whichever is outputting post content in your template) with the following:

    <?php
    $strings = preg_split('/(\.|!|\?)\s/', strip_tags($post->post_content), 2, PREG_SPLIT_DELIM_CAPTURE);
    echo apply_filters('the_content', $strings[0] .  $strings[1]);
    ?>

    the regex (first argument of preg_split()) matches a period, question or exclamation mark with a space, or any non-visible character, right after it. preg_split() will ‘split’ the text string on any of these, assigning each split to the $strings array.

    Thanks to the PREG_SPLIT_DELIM_CAPTURE flag, $strings[1] holds the original punctuation (or in techspeak, the delimiter), which would normally be lost in the split. The limit argument before it (2) just keeps things neat, placing the initial “sentence” in $strings[0],the delimiter in $strings[1], and everything else in $strings[2].

    Finally, echoing it through ‘the_content’ filter assures any post formatting still takes place.

    Reference:
    https://php.net/preg_split

    Thread Starter Jonathan Stegall

    (@jonathanstegall)

    Perfect. I always struggle with preg_split especially, and regular expressions in general. Thanks so much for your help.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Are one-sentence excerpts possible?’ is closed to new replies.