Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm trying to figure out if it's possible to get an excerpt from each post, grabbing the first paragraph from each one. I'm currently using the ACF plugin and have custom post types and custom fields.
Here's my code:

function custom_field_excerpt() {
    global $post;
    $text = get_field('news');
    if ( '' != $text ) {
        $text = strip_shortcodes( $text );
        $text = apply_filters('the_content', $text);
        $text = str_replace(']]>', ']]>', $text);
        $excerpt_length = 20; // 20 words
        $text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
    }
    return apply_filters('the_excerpt', $text);
}

This works great, but it only trims the first 20 words (or however many words you specify), I'm trying to adjust this to pull in the first paragraph of each post instead of the first 20 words. Is this at all possible?

share|improve this question
add comment

1 Answer

up vote 0 down vote accepted

Assuming your paragraphs are marked with <p> tags, which can be set in the ACF field options, the following should work:

function custom_field_excerpt() {
    global $post;
    $text = get_field('news');
    if ( '' != $text ) {
        $start = strpos($text, '<p>'); // Locate the first paragraph tag
        $end = strpos($text, '</p>', $start); // Locate the first paragraph closing tag
        $text = substr($text, $start, $end-$start+4); // Trim off everything after the closing paragraph tag
        $text = strip_shortcodes( $text );
        $text = apply_filters('the_content', $text);
        $text = str_replace(']]>', ']]>', $text);
    }
    return $text;
}

You could also pretty easily modify this to locate the first <br /> tag, if you happen to be storing your ACF data with <br />'s instead of <p>'s.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.