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

2 Answers 2

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

If you add wpautop to that it should still work even if you are not manually marking your articles with paragraph tags because wpautop will automatically convert double line breaks to properly formatted paragraphs for you.

function get_first_paragraph(){
    global $post;
    $str = wpautop( get_the_content() );
    $str = substr( $str, 0, strpos( $str, '</p>' ) + 4 );
    $str = strip_tags($str, '<a><strong><em>');
    return '<p>' . $str . '</p>';
}

If you then want to toggle in the full article you can use this additional function to get everything except for the first paragraph that you already got:

function get_the_post(){
    global $post;
    $str = wpautop( get_the_content() );
    $str = substr( $str, (strpos( $str, '</p>')));
    return $str;
}
share|improve this answer

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.