0

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?

0

2 Answers 2

1

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.

0

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;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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